Adding Scripts and Styles to WordPress the Right Way With Enqueueing

Many of us use styles to alter the look of our website, and scripts to enhance functionality. It is important to note however, that the way you add these scripts to WordPress is just as important as the content of these files. Instead of plopping them into the header or footer file we need to use WordPress’ enqueue functionality.

In this article I’ll show you how to add scripts and styles to your themes and plugins, whether you are creating something on the front-end or in the backend.

What Is Enqueueing?

Enqueueing is a CMS-friendly way of adding scripts and styles to WordPress websites. Multiple plugins you have may use jQuery and other shared scripts. If each plugin linked to these assets separately, chaos would ensue and all your JavaScript could stop working.

By enqueueing scripts you are telling WordPress about the assets you want to add and it will take care of actually linking to them in the header and footer. You can even specify the dependencies of your scripts and styles and WordPress will add them in the correct order.

It takes all the information from what is needed by the core, by your theme and your plugins, creates a list of scripts and styles needed, and outputs them in the correct location.

The Bottom Line

No matter how you attach your assets, the end result will be a <script> or a <link> tag somewhere in your website’s HTML. The example below shows three scripts and two styles loaded on a website:

Functionality-wise, this is perfectly fine ,but let’s not forget that WordPress is tasked with a bit more than what I’ve shown above. There may be a few other scripts and styles hanging around. Since the order you include scripts and styles in matters a lot, if you just start putting them in your theme’s header or footer you may get lost very soon.

In addition, the majority of these scripts are not visible in the your theme’s PHP code. All the scripts WordPress and other plugins need are added via the wp_head() and wp_footer() functions.

Enqueueing Assets Correctly

Enqueueing is a way to let WordPress know about your scripts and their dependencies. Based on this, WordPress works out the placement of the script for you. Since this is all done by code you won’t have to worry about rearranging scripts when you need to add a new one. Let’s go through the scripts in the previous section, adding them by enqueueing:

This code should be placed in the functions.php file of our theme, child theme, or in a plugin file. Note that both scripts and styles are enqueued by attaching a function to the wp_enqueue_scripts hook.

The first two things I enqueued were our styles. I defined our theme style first, even though it depends on the reset style. This is not a problem since I defined this dependency in the third parameter. The first parameter is the unique name of the asset, the second is its location.

The third asset I’ve added is the excellent Owl Carousel. In the third parameter I’ve specified jQuery as a dependency. I do not need to enqueue this myself because it is built into WordPress. Take a look at the WordPress Codex for a list of included scripts.

Finally, I include the theme script. Our script depends on jQuery and Owl Carousel. In reality you could get away with just defining Owl Carousel as the dependency. Since jQuery is a dependency for Owl Carousel it would be included before it in any case. That said, I like to state my dependencies fully, it gives me more information when looking at the code.

The last piece of the puzzle is making sure that our theme script is loaded in the footer. This can be done by defining the fifth parameter as true. The fourth parameter is an optional version number which I’ve set to 1.0.

Enqueueing In Detail

Now that you’ve seen an example, let’s get our hands dirty and look at all the functions and parameters available to us.

We used two functions: wp_enqueue_script() and wp_enqueue_style(). They both take five parameters, sharing the first four:

  • handle: This is the name of your script or style. It is best to use only lowercase letters and dashes here, and make sure to use a unique name.
  • source: The URL of your script or style. Make sure to use functions like get_template_directory_uri() or plugins_uri().
  • dependencies: An array of handles to assets which your script or style depends on. These will be loaded before your enqueued script.
  • version: A version number which will be appended to the query. This ensures that the user receives the correct version, regardless of caching.
  • in_footer: This parameter is only available for scripts. If set to true the script is loaded through wp_footer() at the bottom of your page.
  • media: This parameter is for styles, it allows you to specify the type of media the style should be displayed for. For example: screen, print, handheld, etc.

Hopefully the explanation of the parameters made our example in the previous section that much clearer. You can now start playing around with your own styles and scripts.

Asset Registration

There are actually two steps to adding an asset, but the enqueueing function can get it done in one go. Technically scripts and styles are first registered and then enqueued. Registration lets WordPress know about your assets, while enqueuing actually adds them to the page. Here’s an alternative way to add our Owl Carousel:

So why do this in two steps when one is enough? The answer is that in some cases you don’t register the script in the same place you enqueue it. A good example is shortcodes. Suppose a shortcode you create requires some Javascript. If you enqueue it by attaching it to wp_enqueue_scripts hook it will be loaded on every request, even if the shortcode isn’t used.

The answer is to register the script using the wp_enqueue_scripts hook, but enqueue it in the shortcode function. This will load it only when the shortcode is actually used. If the shortcode is used multiple times the script will only be included once so we’ve covered all the bases.

The wp_register_scripts() and wp_register_styles() functions share the same parameters as their enqueuing brethren. The only difference is the the enqueue functions allow you to specify only the handle as long as that handle has been registered.

Removing Scripts And Styles

WordPress provides dequeueing and deregistering functions for both scripts and styles.

  • wp_deregister_script()
  • wp_deregister_style()
  • wp_dequeue_script()
  • wp_dequeue_style()

These function allow us to remove assets modularly. The following example shows how jQuery can easily be removed and replaced by a more recent version.

That being said, it is almost never a good idea to replace jQuery with a new version. WordPress is built to work as smoothly as possible with the version added to it by default. Replacing it should not be taken lightly.

Summing Up

Hopefully you now see why enqueueing is such an important process. It takes the burden of dependency maintenance off your shoulders and allows you to add your scripts in a modular and manageable way.

Enqueueing is required for all WordPress plugins and themes. Your product (free or premium) will not be accepted into the WordPress repository and many premium marketplaces without it. It forms the basis of “playing nice with others” and should be followed by every developer.

If you have any questions or comments about the process let me know in the comments below.

Image Credit: Xiaojun Deng from Flickr.

11 Responses

  • New Recruit

    Daniel, there are two places where you added script tags, but they’re not appearing in the text. I viewed them in the source code.

    The first is just before this question…

    “So why do this in two steps when one is enough?

    The second is just before…

    “That being said, it is almost never a good idea…”

  • Site Builder, Child of Zeus

    Thank you for posting detailed information about how these things work. I have been trying to figure out how to best use this info about enqueing to deregister a bunch of bloat on my wp+bp site. Currently running this site with some standard plugins like bp-media and the wpmudev buddypress social theme – my site takes over 20 seconds to load each page.

    With the info I found at http://www.wpbeginner.com/wp-tutorials/how-wordpress-plugins-affect-your-sites-load-time/

    I think I can cutout about 75% of the stylesheet requests, and I hope most of the multiple javascript loads.

    I am still confused about registering things on certain pages, and not sure which pages really need all the bloat for rt-media. Now that wordpress is pulling in dashicons and google fonts and rtmedia is pulling so many components, with bp-social making several requests for css and atill adding inline stuff – the load time on this site is horrible. Hopefully doing some of this de-register enque stuff will cut the load time in half.

    I was planning on posting about this in the wpmudev forums to see if anyone has already posted a step by step for weeding out this ridiculous amount of bloat with what must be a fairly standard buddypress setup. I guess I will pop over to the forums and bring this up.

  • Sue
    Site Builder, Child of Zeus

    Daniel, thank you for another wonderful tut. You are one of the many reasons I’m so glad I became a WPMU Dev Premium subscriber. You present things that can be rather complex in a way that makes them very simple to understand, without your reader feeling like an idiot.

    I’m running BuddyPress under the WPMU Studio theme, and have been experiencing horrendous lag as I’ve added in a few new plugins. I’ve been looking for a way to wrangle with this by trying to add in yet another plugin (which I’m loathe to do, because it’s one more variable in the mix when you’re trying to simplify). This single tutorial has given me both the knowledge I need to lighten some of the load, and a very easy way to implement it.

    Thank you so much for what (and -how-) you contribute to the community! You’re a wonderful asset, and I appreciate how much easier you make my job.

    Sue.

  • Hi Sue,

    Thank you so much for the kind words, I’m so happy you enjoyed – and more importantly – benefited from the article. I always try to emphasize that not knowing something, or having incomplete knowledge is nothing to be ashamed of. We’re all good at different things, the willingness to learn should be rewarded, not looked down upon!

    While there is a lot you can do to make your lag go away on the code side and on the plugin side, I would advise looking into managed WordPress hosting. I’ve seen loading times decrease drastically. Of course this is not a substitute for debugging potential issues, but can help alleviate the pain in the short term.

    Thanks again for the kind words :)

    Daniel

  • New Recruit

    I had searched in the web and found this way and this is also working but in the wordpress it is not the correct way to do it Please help me to do it.
    function rara_scripts() {
    wp_enqueue_script(‘jquery’); // just enqueue as its already registered
    if ( is_singular() && comments_open() && get_option( ‘thread_comments’ ) )
    wp_enqueue_script( ‘comment-reply’ );

    /* REGISTER ALL JS FOR SITE */
    wp_register_script(‘rara-skip-link-focus-fix’,get_stylesheet_directory_uri().’/js/skip-link-focus-fix.js’);
    wp_register_script(‘rara-jquery-1.11.2.min’,get_stylesheet_directory_uri().’/js/jquery-1.11.2.min.js’);
    wp_register_script(‘rara-cycle-carousel’,get_stylesheet_directory_uri().’/js/cycle-carousel.js’);
    wp_register_script(‘rara-accordion’,get_stylesheet_directory_uri().’/js/accordion.js’);
    wp_register_script(‘rara-open-close’,get_stylesheet_directory_uri().’/js/open-close.js’);

    /* CALL ALL CSS AND SCRIPTS FOR SITE */
    wp_enqueue_script(‘rara-skip-link-focus-fix’);
    wp_enqueue_script(‘rara-jquery-1.11.2.min’);
    wp_enqueue_script(‘rara-cycle-carousel’);
    wp_enqueue_script(‘rara-accordion’);
    wp_enqueue_script(‘rara-open-close’);

    /* REGISTER ALL CSS FOR SITE */
    wp_register_style(‘rara-all’,get_stylesheet_directory_uri().’/css/all.css’);
    wp_register_style(‘rara-googleapis-font’,’//fonts.googleapis.com/css?family=Ubuntu:400,500,700,300′);
    wp_register_style(‘rara-font-awesome’,get_stylesheet_directory_uri().’/css/font-awesome.css’);

    /* CALL ALL CSS AND SCRIPTS FOR SITE */
    wp_enqueue_style(‘rara-font-awesome’);
    wp_enqueue_style(‘rara-googleapis-font’);
    wp_enqueue_style(‘rara-all’);
    wp_enqueue_style( ‘rara-style’, get_stylesheet_uri(), array(), ‘2015-03-19’ );
    }
    add_action( ‘wp_enqueue_scripts’, ‘rara_scripts’ );

Comments are closed.