Advertisement
Plugins

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

by

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:

Related Posts
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Creative Coding
    Using the Included Password Strength Meter Script in WordPressPassword meter 400
    WordPress uses a pretty nifty password strength script that is used to display whether the passwords you entered in the WordPress admin are: not the same, very weak, weak, medium or strong. Currently this script is only used when creating creating new users and when changing your password in your admin. In this article, I will be teaching you on how to use the WordPress' password strength meter in your own forms.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Adding a New SettingTheme customizer 400
    By now, we've taken a look at what the Theme Customizer is, how it works, and the components that are unique to it. We've even discussed how options are serialized into the database so that we may retrieve them later when using our theme. To that end, it's time for us to begin doing our own work with the Theme Customizer. In this article, we're going to take a look at transports, how they work, and the difference in their two primary methods. Additionally, we're going to introduce our own control into one of WordPress' existing sections and see how it works with the various transport models.Read More…
  • Code
    Cheat Sheets
    The Complete Guide to Proper JavaScript Usage With WordPressJavascript 400
    I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time. When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress? Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.Read More…
  • Code
    Plugins
    Enhancing the Search Form With typeahead.jsTypeahead ltgrey 400
    The WordPress search form doesn't offer any bells and whistles by default. If it's already included in your theme, or you've added the search widget to one of your sidebars, you can attest to that. One way to greatly improve its functionality is to include an autocomplete script to help enhance the efficiency of how relevant search queries are relayed.Read More…