Sometimes you need to load specific scripts or styles (using
wp_enqueue_style) only if a specific Widged is active, or at least you should, instead of loading a custom script and style for a slider for example, even if the slider (displayed in a widget) is active or not.
In fact, I see many Theme or Plugin developers loading a bunch of scripts in the theme without checking if the script is needed or not, yet the solution is so simple! You just need to enqueue the script or style in the
widget method (function) in your Widget class. It will load your script only of the widget is active.
When it comes to the back-end, you can load your Widget admin specific script or style in the
form method (function) in your Widget class. See an example Widget below:
Since the Theme Extras plugin have many custom Widgets (including a slider Widget), loading scripts ONLY when they are needed is important (because your page speed is important for users and SEO as well) and this is the way it’s done so I though I’ll share this with you since almost 100% of the plugins / themes I saw are doing it wrong.
I could go on about the fact that Widgets should belong to Plugins only and you should not be locked-in for using a specific theme if that contains a Widget you need, but that’s another story. 🙂