Update: See Conditional Script Loading Revisited for WordPress 3.3 and newer.

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 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 URL to 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('init', 'register_my_script');
add_action('wp_footer', 'print_my_script');
 
function register_my_script() {
	wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
}
 
function print_my_script() {
	global $add_my_script;
 
	if ( ! $add_my_script )
		return;
 
	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;
 
	static function init() {
		add_shortcode('myshortcode', array(__CLASS__, 'handle_shortcode'));
 
		add_action('init', array(__CLASS__, 'register_script'));
		add_action('wp_footer', array(__CLASS__, 'print_script'));
	}
 
	static function handle_shortcode($atts) {
		self::$add_script = true;
 
		// actual shortcode handling here
	}
 
	static function register_script() {
		wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
	}
 
	static function print_script() {
		if ( ! self::$add_script )
			return;
 
		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 (6)

Comments (41)

  • 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?

      • scribu says:

        $wp_scripts loads dependencies as soon as they’re needed, so jQuery will simply be loaded once, in the header.

  • 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.

  • Dan says:

    but a jedi doesn’t put his scripts in the footer.

    With a shortcode is there no way to add it in the head if the shortcode is present?

  • Dan says:

    Thanks, just fyi I subscribe to the post but never got a reply in my mail unless it was filtered as junk.

    Thanks for your help.

  • Thai says:

    Great overview on how to get your plugin the right way. I was struggling because I’m building my first plugin. I’m basically a Padawan becoming a Jedi Knight after this walk through.

    Thank you so much!

  • Thai says:

    In your add_script() function within the class, are you returning false if $add_scipt is false? I’m having a bit of trouble trying to get my js flag going. I’ve set the flag in the shortcode handler but my add javascript function is having a hard time picking it up? Thank you for your time!

    • scribu says:

      The purpose of the return statement is to prevent further execution. Make sure the variable you’re setting as the flag is the same one you’re checking.

      • Thai says:

        I got it to work and it wasn’t the flag at all. It was me using wp_enqueue_script() and I didn’t realize wp_print_scripts() can process an array of registered handles. I seriously feel like Padawan still. Your write up is such a great method. May the force be with you.

  • This worked great!!

    I tried your method before and could not get it to work at all. I tried it again today and now it works. I must have been using wp_enqueue_script. Not sure what it was before.

    Thank you so much!

  • Lacrymology says:

    what I did was this: I have a different php file that handles the actual content of the shortcode, I include it from the shortcode handler, and call add_action(‘wp_footer’, ‘add_my_javascript’); from there. add_my_javascript doesn’t check any flags, just doesn’t get registered unless the content is being printed. It can be prettified by wrapping in a class, I guess.

  • Michael Simpson says:

    This is an outstanding article and very informative. I put it to good use for my plugin. In addition, I re-wrote the Jedi-Master code to make it object oriented and reusable, so every time I create a new shortcode I can subclass it.

    To use it,
    1. Create a class for a new short that extends ShortCodeScriptLoader, e.g.

    class YourSubclass extends ShortCodeScriptLoader {}

    2. Implement the abstract method handle_shortcode() to do whatever
    3. Implement the abstract method add_script() to add scripts calling wp_register_script() and wp_print_scripts()
    4. Initialize the shortcode like:

    $sc = new YourSubclass();
    $sc->register('shortcode');

    … somewhere in your code where your would normally call add_action().

    Code:

    abstract class ShortCodeLoader {
     
        /**
         * @param  $shortcodeName mixed either string name of the shortcode
         * (as it would appear in a post, e.g. [shortcodeName])
         * or an array of such names in case you want to have more than one name
         * for the same shortcode
         * @return void
         */
        public function register($shortcodeName) {
            $this->registerShortcodeToFunction($shortcodeName, 'handle_shortcode');
        }
     
        /**
         * @param  $shortcodeName mixed either string name of the shortcode
         * (as it would appear in a post, e.g. [shortcodeName])
         * or an array of such names in case you want to have more than one name
         * for the same shortcode
         * @param  $functionName string name of public function in this class to call as the
         * shortcode handler
         * @return void
         */
        protected function registerShortcodeToFunction($shortcodeName, $functionName) {
            if (is_array($shortcodeName)) {
                foreach ($shortcodeName as $aName) {
                    add_shortcode($aName, array($this, $functionName));
                }
            }
            else {
                add_shortcode($shortcodeName, array($this, $functionName));
            }
        }
     
        /**
         * @abstract Override this function and add actual shortcode handling here
         * @param  $atts shortcode inputs
         * @return string shortcode content
         */
        public abstract function handle_shortcode($atts);
     
    }
     
    abstract class ShortCodeScriptLoader extends ShortCodeLoader {
     
        var $doAddScript;
     
        public function register($shortcodeName) {
            $this->registerShortcodeToFunction($shortcodeName, 'handle_shortcode_wrapper');
     
            // It will be too late to enqueue the script in the header,
            // so have to add it to the footer
            add_action('wp_footer', array($this, 'add_script_wrapper'));
        }
     
        public function handle_shortcode_wrapper($atts) {
            // Flag that we need to add the script
            $this->doAddScript = true;
            return $this->handle_shortcode($atts);
        }
     
        // Defined in super-class:
        //public abstract function handle_shortcode($atts);
     
        public function add_script_wrapper() {
            // Only add the script if the shortcode was actually called
            if ($this->doAddScript) {
                $this->add_script();
            }
        }
     
        /**
         * @abstract override this function with calls to insert scripts needed by your shortcode in the footer
         * Example:
         *   wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
         *   wp_print_scripts('my-script');
         * @return void
         */
        public abstract function add_script();
     
    }
  • Abi أب says:

    Is there any function in wordpress to add inline javascript code?

    • scribu says:

      Nope, because you can just do this:

      <?php
      function my_inline_js() {
      ?>
      <script type="text/javascript">
      // JS code here
      </script>
      <?php
      }
      add_action( 'wp_footer', 'my_inline_js' );
  • kavin says:

    Excellent article, scribu.

    I have a question.
    My plugin is in wrapped up in a class (wp-presentation.php), which uses options API through another class(plugin-options.php). The latter file holds plugin_options class, which handles everything related to options page and so is reusable.

    I have the following code in the plugin_options::menu_admin

    $this->page_id = add_options_page( $this->name . ' Options', $this->name, 'manage_options', $this->page_prefix . '-options', array(&$this, 'render_options_page') )
    ;

    As mentioned in the codex, the page prefix can now be used to include the scripts only on plugin page. Well, it should be, right?

    Say, for example that this object has a function set_admin_scripts.

    // From the new instance
    $options_page->set_admin_scripts($array_with_Scripts);
    // array has script handle as the key and value as the url.

    Now following should work, but it doesn’t.

    // IN the plugin_options class
    $this->page_id = add_options_page( $this->name . ' Options', $this->name, 'manage_options', $this->page_prefix . '-options', array(&$this, 'render_options_page') );
     
    foreach( $this->admin_scripts as $handle => $url {
       add_action('admin_print_scripts-' . $page_id, call_user_func_array(
               array( &$this, 'load_admin_scripts'),
               array( $handle, $url)
    ));
    }
     
    } // END function plugin_options::menu_admin
     
     
    function load_admin_scripts($handle, $url) {
         wp_enqueue_script( $handle, $url);
    }

    Am i in the right path, or just too much overcomplicating it? Thanks.

    • scribu says:

      You seem to be confused about how add_action() works.

      Basically, the foreach loop should be within the load_admin_scripts() method.

  • kavin says:

    okay, when i move the foreach loop to the load_admin_scripts, $page_id is not available anymore, the script does not load at all. Or would $_GET['page'] be a simpler alternative?

  • Hi @scribu –

    There’s one change needed to your “Jedi Master” version, and that’s to prefix all your functions with “static”. Hopefully this screenshot can explain more easily:

    http://screenshots.newclarity.net/skitched-20120126-035029.png

    BTW, I’m really excited to see you are advocating static methods for hooks as that’s also the pattern we’ve evolved to and thinks works best; it’s nice to get some external confirmation. It seems Ryan McCue has also selected on that code pattern too.