Using Scripts in widgets

(Naresh Devineni) #1

Fairly recently, I have been working on widget with repeatable fields. I am good with backbone.js, so I created a repeatable fields widget with Backbone.js and Handlebars. After few hurdles I managed it to work properly :relieved:.

But this raised a question :sob:

Isn’t that including scripts in a widget is a bad idea?

At the end of the day, for me it all boils down to standards and easy to use features for wp-admin managers.

So what should I do now ? Should I continue to use Modern Backbone Approach or should I switch back to Plain Javascript ? :fearful:

Any opinion which gives some clarity is highly :heart_eyes:.

(Piet) #2

I’d say if you can find a way to only load the scripts when the widget is actually showing (thus being loaded on the page and not when a widget is present somewhere on the site), then you can use the modern approach.

Half of my time making child themes for clients is spent (read: wasted) on making sure scripts/styles of plugins only load on page that actually contain anything of those plugins. So the more plugin developers that enqueue their scripts/styles only on the right page loads the better place the world becomes :slight_smile:

(Naresh Devineni) #3

Thank you for the opinion :slight_smile: . I will go with the modern approach. I have recently read Justin Tadlock’s “Whistles” plugin code. And It does exactly what you have mentioned. It only loads scripts when the plugin content is loaded in a particular page. I admire and follow his coding standards. Always a joy to read his code :heart_eyes:

(Leland Fiegel) #4

Also, it’s a good idea to be aware of what scripts are already included in WordPress.

Here’s a list of them:

Backbone is one of them, so in case you didn’t know already, be sure to just include that instead of bundling your own version. This helps prevent the same script getting needlessly loaded twice.

(Naresh Devineni) #5

Yeah, I am well aware of that. Thats the first reason why I started creating Backbone based widgets :blush:. Backbone is not going anywhere atleast when it comes to wordpress :heart_eyes: