If you’re involved in WordPress development, a challenge that you’re going to face sooner or later is how to include JavaScript files efficiently.

In this tutorial, I’m going to show you the best way to do that.

Let’s say you have a plugin that adds a custom shortcode. The shortcode needs some JavaScript code which requires jQuery.

If you’re just starting out with WordPress development, you might be tempted to write something like this:

How a WordPress Youngling does it

add_action('wp_head', 'add_my_script');
 
function add_my_script() { ?>
<script type="text/javascript" src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/my-script.js"></script>
<?php }

Let’s see what’s wrong with that approach:

Firstly, since WordPress 2.6, the user can move the wp-content directory wherever he wants. What does that mean? That’s right: instant plugin breakage.

Secondly, if the user installs another plugin that also uses jQuery, the page will end up with jQuery being loaded twice.

Fortunately, WordPress lends us a hand with these two problems:

How a young Padawan does it

add_action('template_redirect', 'add_my_script');
 
function add_my_script() {
	wp_enqueue_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
}

The above script ultimately does what the first one does, except:

  • it gets the correct path for the file
  • it checks if jQuery has already been included or not
  • the script tag is written in the footer, so the page loads faster

That’s an obvious improvement. But what if the shortcode appears on a single page?

You’re needlessly including a file 99% of the time, causing slower page loads.

Notice that in the last two examples, we’ve been using the template_redirect action.

The trouble with wp_enqueue_script() is that you have to call it before wp_head() fires. So, before the page is rendered, you have to decide if you should add your script or not. Not an easy call to make, is it?

Well, there’s a secret method that will let you enqueue scripts after the entire page has been displayed.

The Jedi Knight way

add_action('wp_footer', 'print_my_script');
 
function print_my_script() {
	global $add_my_script;
 
	if ( ! $add_my_script )
		return;
 
	wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
 
	wp_print_scripts('my-script');
}

In this case, the script will be enqueued only if the $add_my_script global was set at some point during the rendering of the page.

The key here is that you’re calling wp_print_scripts() directly, instead of relying on WordPress to do it for you.

It will still check if jQuery was already enqueued or not.

You can set the $add_my_script flag from any function or method, including from a shortcode handler:

add_shortcode('myshortcode', 'my_shortcode_handler');
 
function my_shortcode_handler($atts) {
	global $add_my_script;
 
	$add_my_script = true;
 
	// actual shortcode handling here
}

So, the script will be added if [myshortcode ...] was found in any of the posts on the current page.

Nothing more to do here, except wrap it up in a nice class:

The Jedi Master way

class My_Shortcode {
	static $add_script;
 
	function init() {
		add_shortcode('myshortcode', array(__CLASS__, 'handle_shortcode'));
		add_action('wp_footer', array(__CLASS__, 'add_script'));
	}
 
	function handle_shortcode($atts) {
		self::$add_script = true;
 
		// actual shortcode handling here
	}
 
	function add_script() {
		if ( ! self::$add_script )
			return;
 
		wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
 
		wp_print_scripts('my-script');
	}
}
 
My_Shortcode::init();

I hope this tutorial has helped you on your way to mastering WordPress script loading.

Further reading:

PS: This post was prompted by this question from Artem.

Reactions (1)

Comments (19)

  • Hey scribu, you came up with a great summary.

    I see in your final solution you’re exploiting the fact that it’s OK for JS to load in the footer, and by the time you get to the footer, it’s still OK to print it there. I considered this approach but since it doesn’t work with CSS (it’s bad practice to include CSS in the footer), I decided to pursue something more generic.

    Your approach, however, does have the benefit of not using that extra processing step as well as benefiting from the native shortcode API. Javascript is the more heavyweight component compared to CSS, so it’s a nice compromise for those who are worried.

    One question, however. Could you not just avoid the global $add_my_script flag and the self::$add_script flag by enqueuing the JS files from within your shortcode function and then only doing the printing of the remaining queue in the add_script() function (which should really now be print_script())? I may be missing something subtle here though.

    Thanks,
    Artem

    • scribu says:

      Hello Artem, thanks for stopping by.

      Why I don’t enqueue the script directly in the shortcode function:

      A shortcode can appear more than once on a page (even within a single post), so $wp_scripts would do extra work on each pass.

      Related to CSS handling:

      Since CSS dependencies aren’t so common, I just inject a <link> tag in the header:

      <script type="text/javascript">
      jQuery(document).ready(function($) {
      	$('head').prepend($('<link>').attr({
      		rel: 'stylesheet',
      		type: 'text/css',
      		media: 'screen',
      		href: '<?php echo $css_url; ?>'
      	}));
      });
      </script>
      

      That code would go right after $wp_scripts->do_items().

      • scribu, thanks for the reply. Alright, I can see how calling multiple wp_enqueue_script()s would be a little bit slower (though they wouldn’t create duplicates, obviously) than just setting the flag, so this makes sense.

        The CSS, however, is a bit more problematic. First, you use jQuery which runs after the page loads, which might be too late – might as well just include it in the footer the – it would be downloaded sooner. Also, for people who have javascript disabled, the CSS would never load (but screw them anyway :-] ).

        Btw, I updated my original 2 posts to include a link back here. Good job. Now if only everyone suddenly started following these guidelines…

        • scribu says:

          I tried including the CSS directly in the footer, but Safari doesn’t seem to like that at all.

          Of course, you could do it without jQuery – it was just the code I had lying around.

  • Viper007Bond says:

    Real ninjas do it like this:

    wp_print_scripts( array( 'my-script' ) );

    Much better than using $wp_scripts->do_items(). :)

    My SyntaxHighlighter plugin uses this method BTW. :)

    • scribu says:

      The only reason I don’t use wp_print_scripts() is because it has an associated action, which other plugins might use to to output their own code.

      I think I’ll open a ticket to allow the action to be bypassed.

      Update: And here it is: #11923

  • TobiasBg says:

    One small questions remains for me, regarding the inclusion of jQuery:

    Your code will include jQuery in the footer if it hasn’t been included before. Now, isn’t jQuery required (or at least recommended) to be included in the head?
    Does anybody have insights on this, especially in regards of the latest jQuery 1.4?

    Thanks!

    • scribu says:

      I think that’s more of a mith than fact. I’ve never had any issue while loading jQuery in the footer.

    • Since jQuery runs after the page loads, I think it should be fine. Another question, however, what would happen if jQuery was in the footer but a plugin that uses it in the header? Would this cause a dependency fail?

  • Ciprian says:

    Very nice upgrade of the original post! I like it! keep up the good work ;) .

  • RavanH says:

    Scribu, THANK YOU!

    Sorry for shouting but this is brilliant. Just what I have been looking for since my plugin does indeed load script that for some users might not be needed on every page (shortcode) while for others it will be needed on every page (widget) or most (with widget logic) … Your method will certainly do it for the shorcode and I suppose I can make it work for the widget too, correct?

    Anyway, thanks for sharing this brilliant insight and for writing it so clearly.

    Allard

    P.S. Please let is know what comes from your ticket on wp_print_scripts() ?

    • scribu says:

      Hello Ravan,

      You’re welcome. :)

      Yes, the method works for any function, be it a shortcode handler, a widget callback etc.

      I will post a comment here when the ticket is closed.

      • scribu says:

        I’ve closed the ticket myself, as I’ve came to the conclusion that it’s alright to use wp_print_scripts().

        The examples in the post are updated.

  • Chris Jean says:

    Interestingly, I implemented a near identical solution for a plugin a couple of weeks ago. The key difference is that rather than using a variable to track whether or not to add the script and running the print_my_script each and every time, I add the function to the wp_footer action inside the code that needs the script.

    For example:

    class ... {
        ...
    
        function print_scripts() {
            wp_register_script( ... );
            wp_print_scripts( ... );
        }
    
        function do_stuff() {
            add_action( 'wp_footer', array( __CLASS__, 'print_scripts' ) );
    
            ...
        }
    }

    Of course, if that looks too dirty, a wrapper method could be used to add the function to the action.

    • scribu says:

      Yeah, you rely on the fact that add_action() registers a function only once. It’s faster to write, but it takes slightly more processing time.

  • Richard says:

    Hi scribu,

    Thanks for posting this, it was very useful. However, I’m curious about the way your instantiating your plug-in (although I suppose your not actually creating an object from your class are you, so maybe that’s not instantiation). For a while now I’ve been doing my instantiation by creating an new object from an anonymous function called from the “plugins_loaded” action hook). Could you possibly explain on why you do in the way you do?

    Thanks,
    Richard

    • scribu says:

      Hi Richard,

      In this case, the initialisation is simply

      My_Shortcode::init();

      I will add any actions or filters from there, as needed.

      I work with static classes because it’s cleaner: no global variables, no instances to keep track of etc. It requires PHP5.

      If you do your plugin initialisation on ‘plugins_loaded’, you won’t be able to use register_activation_hook() etc.

      See some of my plugins for more insights.

Respond / add a comment


Subscribe without commenting