Conditionally Load Scripts and CSS in WordPress Plugins That Use Shortcodes

The official way of loading javascript and CSS files in WordPress is by loading your scripts on wp_enqueue_scripts hook. The problem with this approach is that every single plugin you use will be adding its own scripts and CSS even if its used just once in a single post or page. This approach can quickly overload your blog with CSS files and scripts which you don’t use on most pages.

This is especially true for plugins that use shortcodes.

There is an easy way to solve this!

Due to the holes in the official WordPress documentation most developers are not using it.
Others has to develop smart but no longer necessary hacks like this here. The problem with the proposed solution on that page are at least three:

  • Unnecessary complexity in the code
  • Consuming extra server cycles
  • It will sometimes load your scripts when you don’t need them. For example in my theme the solution was still loading the scripts everywhere because of the loop of “Recent posts” in the sidebar.

So, this is far from perfect. Here is the simplest solution:

Call wp_enqueue_script inside the shortcode functions

It’s really that simple and we are starting to use this approach in our WatuPRO. WordPress handles  this from version 3.3 so you need to use the old “load everywhere” solution for older versions.

Here is a code example of this technique from WatuPRO:

[sourcecode language=’php’]
// this is in our init function. If version is 3.3 or lower we just use the official way
$version = get_bloginfo(“version”);
if($version <= 3.3) add_action("wp_enqueue_scripts", "watupro_vc_scripts"); // then in our shortcode handlers we simply call watupro_vc_scripts directly: function watupro_shortcode($attr) { watupro_vc_scripts(); // ..... } [/sourcecode] Inside watupro_vs_scripts() there are all the wp_register_script and wp_enqueue_script calls. This seems to work fine on all versions. If you have any comments, please let me know.

Leave a Reply