The Ins and Outs of The Enqueue Script For WordPress Themes and Plugins

The Ins and Outs of The Enqueue Script For WordPress Themes and Plugins

Tutorial Details
  • Program: WordPress
  • Version : 3.0+
  • Difficulty: Easy
  • Estimated Completion Time: 15 minutes

The wp_enqueue_script function is the best solution for loading JavaScript files into your WordPress site. If you’re developing a theme that uses JavaScript or JavaScript Libraries, the wp_enqueue_script function is the way to go. If you haven’t really used this before though, it can be confusions… so today, we’ll be taking an in depth look into how to properly load scripts into your theme or plugin using the enqueue function.

Subsequent Changes to Techniques & Software

Certain aspects of applications or techniques used in this tutorial have changed since it was originally published. This might make it a little difficult to follow along. We'd recommend looking at these more recent tutorials on the same topic:

Why Do We Use The Enqueue Function?

If you’re coming from a basic HTML background, you’re probably used to simply loading up Javascript files (including anything from jQuery to plugin scripts) directly into the header or footer of your document. That’s fine when you’re in a standalone environment like a basic HTML page… but once you introduce the myriad of other scripts that might potentially run on a WordPress installation, it gets trickier to do what I’ll call “crowd management” with your scripts.

So why not load your JavaScript in the Header or the Footer? The answer is pretty simple: By including your JavaScript like that, you run the risk of having conflicts with your JavaScript across your installation (think, multiple plugins trying to load the same scripts, or different versions of that script). Furthermore, your JavaScript will load on every page, even if you don’t need it to. This will cause an unnecessarily longer load time for you pages, and can interfere with other JavaScript, like from a plugin or within the dashboard… and that’s a No No in WP development.

By using the wp_enqueue_script function. You’ll have better control with how and when you load your JavaScript. You can even decide whether to load into the header or footer.


Understanding the wp_enqueue_script Function

The wp_enqueue_script function is what loads scripts into you WordPress site. You’re usually going to use it in your functions.php file.

The wp_enqueue_script function itself is pretty straight forward, so let’s take a look it’s structure.

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

  • $handle
    • This is the handle (the name) of the script to be loaded. It should be in all lower case.
    • This is Required
    • Default: None
  • $scr
    • This is the URL of the script.
    • If you’re loading locally from your server you shouldn’t hard code the URL for scripts on your server. It’s better to use content_url, bloginfo("template_url"), or get_template_directory_uri() (recommended by the WordPress Function Reference) for themes, and plugins_url for plugins.
      <?php wp_enqueue_script('myscript', content_url('/myTheme/js/myScript.js'__FILE__)); // content_url ?>
      
      <?php wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__); // bloginfo("template_url") ?>
      
      <?php wp_enqueue_script('myscript', get_template_directory_uri().'/js/myScript.js'__FILE__); // get_template_directory_uri() ?>
      
      <?php wp_enqueue_script('myscript', plugins_url('/myPlugin/js/myScript.js'__FILE__)); // plugins_url ?>
                   	
    • If you’re loading your script from another server. For example, loading the jQuery Library from the Google CDN. You just put the URL of the file to be loaded.
      <?php wp_enqueue_script('myscript', 'https://www.url/of/file/script.js'__FILE__); ?>
                   	
    • This is Optional
    • Default: false
  • $deps
    • This is an array that handles any script dependencies. For example, is your fade.js script requires jQuery to run. This parameter will associate your script to the jQuery Library.
    • You use “false” if you don’t want to use this parameter, but want to use other parameters.
      <?php wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), false, '3.1' ); ?>
                      
    • The required script must be loaded first.
    • You use the required script’s handle for the array.
      <?php 
      wp_enqueue_script('jquerylib', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');
      wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array('jquerylib'));
      ?>
              		
    • This is Optional
    • Default: array()
  • $ver
    • This is the version of your script.
    • The version is concatenated to the end of the path as a query string. The version can be the version number, false, or NULL.
    • If you use false for the version. The WordPress version will be used.
    • If you use NULL. Nothing will be used as a version. This is not recommended by the WordPress Function Reference.
    • If you don’t use the $ver parameter.The WordPress version will be used by default.
      <?php wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), false, '1.0' ); ?>
              		
    • This is Optional
    • Default: false
  • $in_footer
    • This will determine where your script is place on the page.
    • This parameter is a boolean (“true” or “false”)
    • By default your script will be placed in the <head >, but it is better to place it right before the close of the <body > tag. This is accomplished by passing “true” to the parameter.
      <?php
      wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array(), 'version', false ); // placed in the head
      wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array(), 'version', true ); // placed before body close tag
      ?>
              		
    • This is Optional
    • Default: false

As you can see, all of the parameters except $handle are optional. At first glance this may seem odd. Especially the $scr parameter. How can WordPress locate the script without a url?

The reason behind this is that WordPress comes with scripts built in. For example jQuery is part of the WordPress core, and the WordPress development team made it super simple to load these built in scripts. All you have to do is pass the script’s handle to wp_enqueue_script.

<?php wp_enqueue_script('jquery'); ?>

For the complete list of built in WordPress scripts and thier handles.Take a look at the WordPress Function Reference.


Using Enqueue Script with Your WordPress Theme

Now that you understand the parts of wp_enqueue_script. Let’s look at how you actually use this with your WordPress theme.

First Things First

There are other WordPress functions that you need to know before you can start enqueing scripts properly.

  • wp_register_script
    • The wp_register_script function is used to register your script with WordPress. What this means is, you will be able to use wp_enqueue_script for your scripts just like the built in scripts that come with WordPress
    • The parameter structure for wp_register_script is exactly the same as the wp_enqueue_script structure, so I’m not going to go over it again. You can reference the section above if needed.
    • Just set up wp_register_script just as you would for wp_enqueue_script. Then enqueue the script with wp_enqueue_script by passing the handle to it.
      <?php
      wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array(), 'version', false );
      wp_enqueue_script('myscript');
      ?>
              		
  • wp_deregister_script
    • The wp_deregister_script removes a registered script.
    • All you need to do is pass the handle to it.
      <?php wp_deregister_script('myscript'); ?>
              		
  • wp_deregister_script
    • The wp_dequeue_script removes a registered script.
    • All you need to do is pass the handle to it.
      <?php wp_dequeue_script('myscript'); ?>
              		

Loading Your Scripts

The easiest way to load your script is to place the wp_enqueue_script where ever you want it on your page.

<?php wp_enqueue_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), false, '1.0' ); ?>
<?php wp_head(); ?>

Easy enough, just not to elegant. A better way, is to use your function.php file to load your scripts. To do this you need to make a custom function. Then use add_action to initialize your function.

<?php 
function load_my_scripts() {
	wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), false, '1.0', true );
	wp_enqueue_script('myscript');
}
add_action('init', 'load_my_scripts');
?>
  • Line 2 creates a function called load_my_scripts
  • Line 3 registers the script myscript
  • Line 4 enqueues the script myscript
  • Line 6 initializes the function load_my_scripts

The script we just loaded needs the current version jQuery to run, so let’s deregister the default version that comes with WordPress add the new version to our function.

<?php 
function load_my_scripts() {
	wp_deregister_script( 'jquery' );
	wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');
	wp_enqueue_script('jquery');
	wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array("jquery"), '1.0', true );
	wp_enqueue_script('myscript');
}
add_action('init', 'load_my_scripts');
?>
  • Line 2 deregisters the default jQuery that comes with WordPress
  • Line 3 registers another version of jQuery
  • Line 4 enqueues the script myscript

OK, good practices for WordPress coding dictates we need to check if a function exists before we run it. This is accomplished like this.

<?php 
if (function_exists('functionName')) {
}
?>

This checks if your function already exists.If it doesn’t, it’ll run your function.

Let’s add this to our load_my_scripts function

<?php 
if (function_exists('load_my_scripts')) {
    function load_my_scripts() {
		wp_deregister_script( 'jquery' );
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');
		wp_enqueue_script('jquery');
		wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array('jquery'), '1.0', true );
		wp_enqueue_script('myscript');
    }
}
add_action('init', 'load_my_scripts');
?>

Now, if you go to your admin page you don’t want your script to load. It might cause a conflict and break the admin page. A general rule of thumb is that you don’t want your custom scripts to load in the admin page. Scripts for plugins is a different story. I’ll go over that later.

We’re going to check if the page loaded is not the admin page with !is_admin(). If it’s not, our scripts will load.

<?php 
if (!is_admin()) {
}
?>

Now the function looks like this.

<?php 
if (function_exists('load_my_scripts')) {
    function load_my_scripts() {
    	if (!is_admin()) {
		wp_deregister_script( 'jquery' );
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');
		wp_enqueue_script('jquery');
		wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array('jquery'), '1.0', true );
		wp_enqueue_script('myscript');
    	}
    }
}
add_action('init', 'load_my_scripts');
?>

There you go. A nice template for you to use for you to enqueue scripts


Using Enqueue Script for Your Plugins

OK, now that you got that down. Let’s add a script that will only load on your plugin’s admin page.

It’s actually very simple. Just write your script function just like the on we did in the previous section in your plugin’s file. Only now instead of using ‘init’ in the add_action, use ‘admin_init’.

<?php 
if (function_exists('load_my_scripts')) {
    function load_my_scripts() {
    	if (!is_admin()) {
		wp_deregister_script( 'jquery' );
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js');
		wp_enqueue_script('jquery');
		wp_register_script('myscript', bloginfo('template_url').'/js/myScript.js'__FILE__), array('jquery'), '1.0', true );
		wp_enqueue_script('myscript');
    	}
    }
}
add_action('admin_init', 'load_my_scripts');
?>

That’s it, now your script will only load when you go to you plugin’s admin page.


Conclusion

I hope this will help you better understand Enqueue Scripts within WordPress, so now you can get out there and load some scripts of your own!

If there is anything you don’t understand or would like to read up on. I recommend visiting the WordPress Codex. Here’s a list of some other relevant codex links for ya as well:

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://Maxlipman.com Max Lipman

    Will have to try it :)

  • http://andrewjtalcott.com/ andrewjtalcott

    “though, it can be confusions” – LOL i bet.

  • http://pippinsplugins.com Pippin

    Great job on this one. A couple of notes:

    1. You should use the “wp_print_scripts” and “admin_print_scripts” hooks instead of “init” and “admin_init” hooks.

    2. Instead of just placing your register and enqueue functions inside of the is_admin() conditional, you should ONLY load the scripts when on your plugin’s admin page, not just when in the admin.

  • she-codes

    Why exactly do you need to check if a function exists when the functions starts on the next line?

    I cannot get it, am I being really dumb?

    And you have reeeally uneven number of brackets.

    • http://gorelative.com Mike DeVita

      because it may already be defined prior.

    • http://austinhinderer.com Austin Hinderer

      It looks like that is a typo, and it should actually say:

      if (!function_exists(‘load_my_scripts’))

      Instead of

      if (function_exists(‘load_my_scripts’))

      • http://austinhinderer.com Austin Hinderer

        Correction, it’s there for backwards compatibility support. It checks with WordPress to see if that function is available.

    • Jason Witt

      Thank you for pointing that out. It’s my spell check. It’s messes with my code all the time. Austin Hinderer
      is right it should be

      if (!function_exists(‘load_my_scripts’))

      If the function doesn’t(! = not) exists.

      • Brian

        Can you please fix it? Not everyone is going to be reading the comments.

        This whole line doesn’t even compile and it’s repeated throughout the article:
        wp_register_script(‘myscript’, bloginfo(‘template_url’).’/js/myScript.js’__FILE__), array(‘jquery’), ’1.0′, true );

        I’m sorry to say, but this article is riddled with errors.

  • http://Www.mojowill.com Themojowill

    Good article although worth noting if you enqueue in your functions.php using the init hook you can’t then use conditional tags to deteine if it should only load on certain pages. Wp_print_scripts will however allow you to use conditional tags inside your enqueue function meaning you can load the JavaScript only on the page templates etc that you need.

  • http://www.3rdwavemedia.com Xiaoying

    Thank you for the great article! It’s very helpful.

    However, instead of using the “init” hook, WordPress’s Codex uses “wp_enqueue_scripts” for adding scripts to the front-end, and it explains as below:

    by using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.

    Source: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    So I guess “wp_enqueue_scripts” hook is good for adding scripts to the front-end, as you don’t need to check “if (!is_admin())” anymore…

  • http://gorelative.com Mike

    i use this along with wordpresses register style function to load all of my theme’s styles and scripts. That way if i have sub themes its easier for me to have one location for them all.

  • http://austinhinderer.com Austin Hinderer

    Based on the comments here, I made some tweaks to the boilerplate you’ve provided. For some reason I was getting an error message with using the “__FILE__” portion of the code, so I decided to get rid of it en lieu of assigning the template location to a variable. I also added a ‘!’ in front of the function_exists function as I wasn’t sure what the thinking was in the article regarding this check. Does anyone see any major functionality issues with using this code instead?

    • http://austinhinderer.com Austin Hinderer

      Forgot the code

      if (!function_exists(‘SCRIPTNAME’)) {
      function SCRIPTNAME() {
      $JscriptURL = get_template_directory_uri().’/js/’; //Sets Javascript directory URL

      //Loads for all pages
      wp_deregister_script(‘jquery’);
      wp_register_script(‘jquery’, (“https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js”), ’1.6.4′, true);
      wp_enqueue_script(‘jquery’);
      wp_register_script(‘scriptHandle’, ($JscriptURL.’functions.js’), array(‘jquery’), ’1.0′, true);
      wp_enqueue_script(‘scriptHandle’);
      }
      }
      add_action(‘wp_enqueue_scripts’, ‘SCRIPTNAME’);

    • http://www.nomad-one.com nomadone

      I found similar errors with your code Austin, but I realised it’s due to some incorrect quote characters being generated by the HTML probably that the code isn’t working

  • http://www.nomad-one.com nomadone

    I also keep getting errors with that Line Austin, Will give your boilerplate a spin

    thanks

  • Pingback: Load jQuery From Google CDN With Local Fallback For WordPress | Wptuts+

  • http://www.designtank.ws Chris Raymond

    Thanks for this article. I just wish I understood enough to figure out how to fix the WP theme I bought from Wizy_lab, which instead of using enqueue script, creates its own wizy_lab functions to load jquery a second time for its theme functions, which means my theme now loads the jquery library twice.

    My attempts to fix this issue led nowhere and unfortunately the theme author has stopped offering support (and even when he did, often ignored issues for weeks).

    In this theme’s includes/framework/extensions, in extension.header.php

    function wizy_scripts($script = ‘jquery’){

    $js_begin = ‘<script type=”text/javascript” src=”‘;
    $js_end = ‘”></script>’ . “\n”;

    // sets stylesheets depending on inputed parameter
    switch($script){
    case ‘jquery’:
    $js = $js_begin . ‘https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js’ . $js_end;
    break;

    case ‘gridnik’;
    $js = $js_begin . INC_URI . ‘/js/gridnik.js’ . $js_end;
    break;

  • http://wpconsult.net Paul

    As others commented, the article is passing on bad practices.
    I recommend reading this Codex article instead:
    http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    Also, if loading libraries from Google, use the same version as WordPress is to avoid any breakage.

  • darren

    You have a syntax error “__FILE__)” multiple times throughout the article.

  • Pingback: How to Enqueue Scripts in WordPress « JohnRegan3

  • vrob

    How do you use the conditionals to make your scripts only load on the pages you need them to?

  • Pingback: » Standing on the Shoulders- Some jQuery and Wordpress Tips

  • Pingback: Getting Loopy - Ajax Powered Loops with jQuery and WordPress | Wptuts+

  • Pingback: Getting Loopy – Ajax Powered Loops with jQuery and WordPress | Graphfucker

  • http://www.gradientpixels.ca Andre

    Great article, but no matter what method I do from this, I get server error 500… until I remove the __FILE__ from the string, which seems to be the issue. I use prettyPhoto in my themes and it loads without the __FILE__ and as soon as I attach that, a nice 500 error shows up.

  • Alex

    Like everyone says, great article, nice explanation. You say that typically you’d load wp_enqueue_script in the functions.php … but isn’t that counter intuitive if you want to selectively load the script, since functions.php’s functions are loaded on every page load? Or is wp_enqueue_script sort of like a neutral loading dock where it’s available but doesn’t load?

  • http://www.rabbitdigital.com Wozzza

    It didn’t work for me either!

    :-(

  • Pingback: Einfaches Enqueuen von Stylesheets | Stefans Blog

  • Pingback: Wordpress and jquery how do I call upon it. - Quora

  • http://jilinteractive.net/ fano

    Every time I want to quickly get a snippet from the envato network, I end up spending more time fixing it before i can use it.
    Here is a working version guys:

    function load_my_scripts() {
    if (!is_admin()) {
    // get jquery library from Google CDN
    wp_deregister_script(‘jquery’);
    wp_register_script(‘jquery’, ‘http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js’);
    wp_enqueue_script(‘jquery’);

    // get jquery-ui from Google CDN
    wp_deregister_script(‘jquery-ui’);
    wp_register_script(‘jquery-ui’, ‘http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js’, array(‘jquery’), false);
    wp_enqueue_script(‘jquery-ui’);

    // gey jquery-ui stylesheet from Google CDN
    wp_enqueue_style(‘jquery-ui-smoothness’, ‘http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css’);

    // get your custom javascript file using jquery
    wp_register_script(‘jquerycustom’, get_bloginfo(‘template_directory’).’/js/jquery.custom.js’, array(‘jquery’), false );
    wp_enqueue_script(‘jquerycustom’);
    }
    }
    add_action(‘init’, ‘load_my_scripts’);

  • http://expertpixels.com/ Expert Pixels

    Cheers for this, any chance in the future you could explain how to enqueue .css files for the admin area of the wp-admin section ? i am just having trouble adding some styling to a custom infobox ive added in the dashboard section.

  • Pingback: Javascript and Ajax Error on Website After Installing Plugins | Tribulant Software Blog

  • Pingback: AJAX and Jquery Conflicts | Documentation

  • http://samlh.com Sam

    Just flagging this for readers/Googlers — when building the javascript file’s url, get_stylesheet_directory() worked better than bloginfo(‘template_url’) for me. Note: I am using a child theme, if that’s relevant.

    I ran into trouble using bloginfo(‘template_url’), since, for whatever reason, that line of code made the browser print the directory path in the browser window. Not sure why this is, but the get_stylesheet_directory() function worked better for me.

  • http://www.fantasyfootballxtreme.com Aaron

    This is a great article.

    I’m trying to create a functions.php file that will over-write any plugins that feel inclined to include their js/css files on every single page thus impeding the page load performance times instead of just loading when it’s required.

    Any ideas how i might do this? I’ve tried just de_registering and de_queueing, but, it doesn’t seem to work. I have a feeling it’s because the order of which the add_action’s work?

    Anyone have any ideas on how to do this?

    Thanks,

  • http://www.blackbookoperations.com/ Black Book Operations

    Just checking, shouldn’t it be

    if (!function_exists(‘load_my_scripts’)) (with the “!”)
    instead of
    if (function_exists(‘load_my_scripts’))

    Or is my logic a bit flawed here?

    Nice insightful article still, explains it loud n clear ;)

    • http://twitter.com/Smartik89 Smartik

      Exactly, “!” makes sure that the function doesn’t exist and if is true it can run the function.

      • http://wp.tutsplus.com/ Japh

        That was rectified in the tutorial sometime ago, however, as the notice at the top of this tutorial says, its content is out of date. You should instead read our How to Include JavaScript and CSS in Your WordPress Themes and Plugins tutorial.

        • http://www.blackbookoperations.com/ Black Book Operations

          Thanks for the new link ;)

  • Pingback: Guida Wordpress – Integrare una Gallery jQuery | Fedeweb

  • Krunal Sojitra

    hi,

    use this one copy and past in yu function.php ans see the megic……………………….

    function load_my_scripts() {
    wp_deregister_script(‘jquery’);
    wp_register_script(‘jquery’, ‘http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js’, false, ’1.7.2′);
    wp_enqueue_script(‘jquery’);
    wp_register_script(‘scripts’, get_template_directory_uri() .’/js/scripts.js’, array(‘jquery’), ’1.0′, true );
    wp_enqueue_script(‘scripts’);
    }

    add_action(‘init’, ‘load_my_scripts’);

  • http://twitter.com/greaveselliott Elliott Greaves

    I am testing a buddypress theme I am developing on a wamp server.

    My enqueue_Script/Style functions work fine when viewing the theme on the PC the wamp server is installed on.

    I run into issues when I am accessing the wordpress installation over the local area network from another PC, Tablet Device or Smartphone as content_url, bloginfo(“template_url”), get_template_directory_uri() all return a string that includes http://localhost/ at the beginning, This works fine on the machine that’s running the localhost testing environment but for other users on the network it causes a 404 as http://localhost does not exist.

    If anybody knows of a solution to this problem it would be greatly appreciated.

    Thank you for reading, and thank you your time.