Avoiding the Problem

WordPress includes these libraries so that plugin and theme authors can avoid this problem by using the wp_register_script and wp_enqueue_script PHP functions to include JavaScript in the HTML.

Registering a file alone doesn’t do anything to the output of your HTML; it only adds the file to WordPress’s list of known scripts. As you’ll see in the next section, we register files early on in a theme or plugin where we can keep track of versioning information.

To output the file to the HTML, you need to enqueue the file. Once you’ve done this, WordPress will add the required script tag to the header or footer of the outputted page. More details are provided later in this article.

Registering a file requires more complex code than enqueueing the files; so, quickly parsing the file is harder when you’re reviewing your code. Enqueueing the file is far simpler, and you can easily parse how the HTML is being affected.

For these techniques to work, the theme’s header.php file must include the line <?php wp_head(); ?> just before the </head> tag, and the footer.php file must include the line <?php wp_footer(); ?> just before the </body> tag.

Registering JavaScript

Before registering your JavaScript, you’ll need to decide on a few additional items:

the file’s handle (i.e. the name by which WordPress will know the file);

other scripts that the file depends on (jQuery, for example);

the version number (optional);

where the file will appear in the HTML (the header or footer).

This article refers to building a theme, but the tips apply equally to building a plugin.

Examples

We’ll use two JavaScript files to illustrate the power of the functions:

The first is base.js, which is a toolkit of functions used in our example website.

The base.js file relies on jQuery, so jQuery can be considered a dependency.

This is the first version of the file, version 1.0.0, and there is no reason to run this file in the HTML header.

The second file, custom.js, is used to add the JavaScript goodness to our website.

makeRed('*');

This custom.js file calls a function in base.js, so base.js is a dependency.

Like base.js, custom.js is version 1.0.0 and can be run in the HTML footer.

The custom.js file also indirectly relies on jQuery. But in this case, base.js could be edited to be self-contained or to rely on another framework. There is no need for jQuery to be listed as a dependency of custom.js.

It’s now simply a matter of registering your JavaScript using the function wp_register_script. This takes the following arguments:

$handle
A string

$source
A string

$dependancies
An array (optional)

$version
A string (optional)

$in_footer
True/false (optional, default is false)

When registering scripts, it is best to use the init hook and to register them all at once.

To register the scripts in our example, add the following to the theme’s functions.php file:

We have used CSS3 media queries to prevent mobile browsers from parsing our desktop style sheet. But Internet Explorer versions 8 and below do not understand CSS3 media queries and so will not parse the desktop CSS either.

IE8 is only two years old, so we should support its users with conditional comments.

Conditional Comments

When registering CSS using the register and enqueue functions, conditional comments are a little more complex. WordPress uses the object $wp_styles to store registered style sheets.

To wrap your file in conditional comments, add extra information to this object.

For Internet Explorer 8 and below, excluding mobile IE, we need to register another copy of our desktop style sheet (using the media type all) and wrap it in conditional comments.

In the code sample above, /* *keep reading* */ would be replaced with the following:

Unfortunately, there is no equivalent for wrapping JavaScript files in conditional comments, presumably due to the concatenation of JavaScript in the admin section.

If you need to wrap a JavaScript file in conditional comments, you will need to add it to header.php or footer.php in the theme. Alternatively, you could use the wp_head or wp_footer hooks.

Outputting The Style Sheet HTML

Outputting the style sheet HTML is very similar to outputting the JavaScript HTML. We use the enqueue function and run it on the wp_print_styles hook.

In our example, we could get away with telling WordPress to queue only the style sheets that have the handles theme-desktop and theme-desktop-ie. WordPress would then output the mobile/all media version.

However, both style sheets apply styles to the website beyond a basic reset: mobile.css builds the website for mobile phones, and desktop.css builds on top of that. If it does something and I’ve registered it, then I should enqueue it. It helps to keep track of what’s going on.

What’s The Point?

You may be wondering what the point is of going through all of this extra effort when we could just output our JavaScript and style sheets in the theme’s header.php or using the wp_head hook.

In the case of CSS in a standalone theme, it’s a valid point. It’s extra work without much of a payoff.

But with JavaScript, it helps to prevent clashes between plugins and themes when each uses a different version of a JavaScript framework. It also makes page-loading times as fast as possible by avoiding file duplication.

WordPress Frameworks

This group of functions can be most helpful when using a framework for theming. In my agency, Soupgiant4, we’ve built a framework to speed up our production of websites.

As with most agencies, we have internal conventions for naming JavaScript and CSS files.

When we create a bespoke WordPress theme for a client, we develop it as a child theme5 of our framework. In the framework itself, we register a number of JavaScript and CSS files in accordance with our naming convention.

Adding CSS and JavaScript to our themes the WordPress way enables us to keep track of exactly what’s going on at a glance.

A Slight Limitation

If you use a JavaScript framework in your theme or plugin, then you’re stuck with the version that ships with the current version of WordPress, which sometimes falls a version or two behind the latest official release of the framework. (Upgrading to a newer version of the framework is technically possible, but this could cause problems with other themes or plugins that expect the version that ships with WordPress, so I’ve omitted this information from this article.)

While this prevents you from using any new features of the framework that were added after the version included in WordPress, the advantage is that all theme and plugin authors know which version of the framework to expect.

A Single Point Of Registration

Register your styles and scripts in a single block of code, so that when you update a file, you will be able to go back and update the version number easily.

If you use different code in different parts of the website, you can wrap the logic around the enqueue scripts.

If, say, your archive pages use different JavaScript than the rest of the website, then you might register three files:

base JavaScript (registered as theme-base),

archive JavaScript (registered as theme-archive),

general JavaScript (registered as theme-general).

Again, the base JavaScript adds nothing to the website. Rather, it is a group of default functions that the other two files rely on. You could then enqueue the files using the following code:

Using The Google AJAX CDN

While using JavaScript the WordPress way will save you the problem of common libraries conflicting with each other, you might prefer to serve these libraries from Google’s server rather than your own.

Using Jason Penny’s Use Google Libraries6 plugin is the easiest way to do this. The plugin automatically keeps jQuery in noConflict mode.

Putting It All Together

Once you’ve started registering and outputting your scripts and styles the WordPress way, you will find that managing these files becomes a series of logical steps:

Registration to manage:

version numbers,

file dependencies,

media types for CSS,

code placement for JavaScript (header or footer);

Enqueue/output files to HTML:

logic targeting output to specific WordPress pages,

WordPress automating dependencies.

Eliminating potential JavaScript conflicts from your WordPress theme or plugin frees you to get on with more important things, such as following up on sales leads or getting back to that hash-tag game that was so rudely interrupted.

Related Articles

Leon

Thanks for this info—finding this level of detail has been difficult for me.

I need to be able to add conditional javascript to my theme the ‘proper’ way for it to get approval from the theme directory. Just sticking the conditional comments in header.php means it won’t get through.

Gabriele Romanato

Most developers simply ignore the fact that they can use self-executing functions to create a new namespace inside their application. So (function($) {…})(jQuery) operates on jQuery, but you can use the same principle to include your library code: (function() { var MyLib = {};)(); It is safe to use jQuery within that context, because it’s like a sandbox.

Another thing to keep in mind is the order by which jQuery plugins are executed: generally, they all use the ready() event, so you may have multiple ready() calls. You can tackle this by creating an autoload method and wrap the plugin calls within the methods of your library:

var MyApp = new function() {

this.twitterPlugin = function() {
…
};

// other plugin calls

this.autoload = function() {

for(var i in this) {

if(typeof this[i] === ‘function’ && this[i] !== arguments.callee) {

this[i]();

}

}

};
}();

Then you’ll have a single call:

$(function() {

MyApp.autoload();

});

Generally is better to include all the JavaScript code at the end of the page for a better perceived performance (see Steve Souders, Yahoo! team), but there may be some plugins that need a different source placement.

Another thing to keep in mind, if you use web fonts, is that your include CSS must come before the CSS that uses it. This is the case of Google Web Fonts. Also consider the fact that this kind of CSS may actually negatively affect the performance of your site if the requested font is not available. Browsers, in this case, tend to freeze and slow down the rendering of the page.

Edouard Duplessis

a better hook to use is “template_redirect” for loading your js or css

1 it’s loading only in front end… so no ” if(!is_admin()) ”
2 You know which template file is loading so if you need a conditionnal loading you have it.
if(is_home()){
wp_enqueue_style(‘home’);
}else{
wp_enqueue_style(‘page’);
}

and if you use a parent theme for development

register your style or script in “after_setup_theme” hook in your parent theme
and in your child register it in “after_setup_theme” but in level 12, so it register after your parent theme.

And for a WordPress for developers, read the book “Professional WordPress Plugin Development” by Brad Williams, Ozh Richard, Justin Tadlock

jimmy

Edwin Kwan

I’m not really getting how registering your javascript and css will prevent conflicts. There’s still the potential for conflicting javascripts and css as it doesn’t stop a plugin for registering their own copy of jquery and have a second plugin use wordpress’ jquery and you’re back to the same problem?

Duncan

What would be the best why to add a chuck of code in the head of the site. I’m registering the main script the way you described above but would like to know the correct way of adding something like the example below:

Peter Wilson

You would be better off putting it in the site’s main JavaScript file rather than outputting it in the HTML. If you must put it in the HTML, attach the function to the wp_footer hook – instead of wp_head – your jQuery doesn’t run until the DOM has fully loaded.

0

16

Chris Raymond

This one caught me. All the Wizylab Premium themes seem to have created their own wizy_functionname including to call jquery. So now my blog loads jquery twice. Since I am not a php coder I have not been able to figure out how to modify the Wizylab Gridnik theme to properly enqueue and register scripts, though I did at least get it to load the same version of jquery as what comes with WP.

0

17

Tominari

saurabh

En queuing the mobile.css (using the function mytheme_enqueue_styles()) was’nt necessary as it will get automatically loaded bcoz it is required the desktop.css style sheet just as in the previous example we did not enquqe the jquery…

Subscribe to our email newsletter for useful tips and valuable resources, sent out every second Tuesday.

Meet Smashing Book #5, our new book on real-life responsive design. With front-end techniques and patterns from actual projects, it's a playbook to master all the tricky facets and hurdles of responsive design. Save 25% today.

Fixing RWD issues can be quite easy — once you understand exactly why they come up. The Mobile Web Handbook will help you understand technical issues on mobile and how to deal with them effectively.

Hungry for more content? Over 60 eBooks are waiting to be discovered in our lovely Smashing Library. And guess what? You can watch Smashing Conference talks there, too.

SmashingConf isn't the eighth wonder of the world, but we are pretty close. Join us at at the shores of Santa Monica for SmashingConf LA on April 27–30 or at SmashingConf NYC on June 15–18. You won't be disappointed.