Skip to main content

jQuery & WordPress

Using jQuery in WordPress can be a tad tricky. WordPress actually comes with a version of jQuery built-in, though it’s not necessarily the most recent version and it doesn’t automatically get loaded for people who visit your site.

Today, I want to show you how to replace the built-in version of jQuery with a CDN hosted version. I’ll also show you an easy way to load your own javascript files in the footer for better performance.

Note: This article was updated on March 3, 2013 to include HTTPS support.

Updated on August 15, 2013: I’ve since switched to using this snippet of code from Travis Smith instead. It uses the Google CDN version of jQuery, but falls back to the local version built into WordPress if it fails.

Using a CDN hosted version of jQuery

Here’s the snippet of code you need to add to your functions.php file…

// Create the my_scripts_method function
function my_scripts_method() {
    // Deregister the built-in version of jQuery
    wp_deregister_script('jquery');
    // Register a CDN hosted version. If browsing on a secure connection, use HTTPS.
    wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js', false, null, true);
    // Activate the jQuery script
    wp_enqueue_script('jquery');
}
// Tell WordPress to run the my_scripts_method function
add_action('wp_enqueue_scripts', 'my_scripts_method');

You’re doing a few things in the above code. First, you’re creating a function named my_scripts_method. In that function, you’re deregistering the built-in version of jQuery, and then registering the version Google hosts in its place.

Finally, you’re telling WordPress to activate that version. The add_action script tells WordPress to run the function you’ve created.

Adding your personal javascript file

If you’re loading jQuery on your site, chances are you’re running your own javascript plugins. If those are going to be used throughout the site, it’s a good idea to put them in an external file that can be cached by browsers for faster loading.

You can use the my_scripts_method function above to do that, too. We’ll be adding the following pieces of code to the function above:

wp_register_script('my-js', get_template_directory_uri() . '/YOUR-JS-PATH.js', false, null, true); 
wp_enqueue_script('my-js');

I host my javascript files in a subfolder of my theme files. get_template_directory_uri() references my theme URL. If you include your javascript file elsewhere, change the URL accordingly. The remainder of the path is the subfolder and file name. On my site, that section is written as get_template_directory_uri() . '/js/gmt.js'.

You’ll notice that at the end of the registration snippet, it says “true.” This variable determines whether or not the file will be included in the footer. I have mine set to true, because footer loading is better for performance. If your file needs to be loaded in the header, change it to “false” or remove it altogether (false is the default).

Here’s what the final version of the function should look like.

// Create the my_scripts_method function
function my_scripts_method() {
    // Deregister the built-in version of jQuery
    wp_deregister_script('jquery');
    // Register a CDN hosted version. If browsing on a secure connection, use HTTPS.
    wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js', false, null, true);
    // Activate the jQuery script
    wp_enqueue_script('jquery');
    // Register your javascript file
    wp_register_script('my-js', get_template_directory_uri() . '/YOUR-JS-PATH.js', false, null, true);
    // Activate your javascript file
    wp_enqueue_script('my-js');
}
// Tell WordPress to run the my_scripts_method function
add_action('wp_enqueue_scripts', 'my_scripts_method');

15 Comments

Leave a comment or contact me on Twitter at @ChrisFerdinandi.


weaponx

I’ve seen and I’ve tried so many solutions and variations, and this is the only one which is complete and which actually works (in my case).
Thank you very much for sharing this.


weaponx

Just 1 question:

Since I have many pages and a lot of different .js files (1 file per page), I need to load only the file which is needed on a certain page instead to load all of them together – for example only aaa.js loads on page1, only bbb.js loads on page2, etc…

Do you know how to achieve this?


Chris Ferdinandi

You can definitely do that. Here’s an abridged example:

function my_scripts_method() { 
    // If it's a particular page
    if ( is_page('PAGE NAME OR ID') ) {
        // Registers your javascript file
        wp_register_script('js-1', get_template_directory_uri() . '/YOUR-JS-PATH.js', false, null, true); 
        // Activates your javascript file
        wp_enqueue_script('my-js'); 
    }
}
// Tells WordPress to run the my_scripts_method function
add_action('wp_enqueue_scripts', 'my_scripts_method'); 

You would add an if ( is_page($page) ) statement within the function for each file you wanted to load conditionally. The $page value can be the page title (ex. 'about'), or the ID. Learn more in the WordPress Codex.

As an aside, depending on how big each JS file is, you might be better off just combining them all into a single file you load once. The browser will cache it, and the visitor won’t need to download that additional file on each subsequent page load. More on that sort of thing on my High Performance Websites article.


weaponx

That solution with if ( is_page(‘PAGE NAME OR ID’) works perfectly. That was exactly what I needed, because my js files are like 1-2kb, but I have well over 100 files and pages. In that case, there is no plugin or other optimization / compression method which would solve this better – just stick with small files and load each individually when it’s needed.
Now my pages loads like 100x faster. Still takes sometimes 1-2 seconds, but that should vanish with better hosting.

Thank you so much for your help and best of luck!


peder

This doesn’t solve the problems with other plugins which uses WP’s ‘non conflict mode or??


Chris Ferdinandi

Hi Peder – I’m not sure I understand your question. No Conflict Mode is a jQuery technique, though the bundled versions of jQuery included by WordPress force you to use it. Whether you use a CDN version of jQuery or the version WP includes, No Conflict Mode scripts will work. With a CDN version, scripts that aren’t No Conflict will also work.


weaponx

Hi Chris, is it also possible to include .css file within this function, like this:

wp_register_script('jquery.upvote', get_template_directory_uri() . '/jquery.upvote.css', false, null, true);
wp_enqueue_script('jquery.upvote');

or it needs to be included in some other way?

I’m trying to make this plugin to work and I’m not sure where is the “leak” (I’ve changed jquery url from 1.9.0 to 2.0.2 in the beginning of the function, so at least that shouldn’t be the cause of the problem).


Chris Ferdinandi

For that you’ll want to use wp_enqueue_style. It has a slightly different structure to it:

wp_register_style( 'jquery.upvote', get_template_directory_uri() . '/jquery.upvote.css', '', false, all);
wp_enqueue_style('jquery.upvote');

weaponx

Thank you very much, it works. Plugin itself (.js) still doesn’t work, but at least we eliminated 1 problem.
If you have time, maybe you can help me with this too.

My guess is that there is a problem in initiation of this function. I’ve put in other .js file this code:

(function($){
    $(document).ready(function(){
	
$('#topic').upvote();
var callback = function(data) {
    $.ajax({
        url: '/vote', //I don't have this url, idk if this needs to be changed to something else
        type: 'post',
        data: { up: data.upvoted, down: data.downvoted, star: data.starred }
    });
};
    });
})(jQuery);

I also changed the jquery.upvote.js location to theme’s folder, where the .css and images folder are located, and I uploaded and registered jquery-2.0.2.min.js just in case.


weaponx

How to disable plugin on specific page? I’ve tried to put this in your function:

if ( is_page('random page') ) {
    deactivate_plugins( '/wp-photo-album-plus/wppa-setup.php', true );
  }

and it gives me fatal error.


Chris Ferdinandi

Three things:

1. AJAX in WordPress is an interesting thing. I would start by Googling how to use it. I’ve always run into trouble adding AJAX scripts via an external file, and have ended up printing them inline instead. Here’s an example of how you might do that: http://ideasandpixels.com/wp_enqueue_script-inline-script-to-load-after-jquery

2. You can’t deactivate plugins on a per-page basis. They’re either on or they’re off. You can, however, make the functions within them conditional based on the page:

function someFunction() {
    if ( ! is_page( 'random-page' ) ) {
        // Add the function content
    }
}

3. While I’m certainly happy to help, I would recommend that for some of these broader questions not related specifically to loading a CDN jQuery file on WordPress, you might start with Google, or dig through the questions on StackOverflow. There’s a good chance if you’re curious about it, someone else is too and has already come up with an answer.

Best of luck!


Azizul Haque

Hello Chris!

I read out your posts and comments. I understand them well. They all are very useful tips.

But I am trying to solve a problem in my client theme. In the theme when I activate Async js & css plugin, it stops other few plugins. I think this is for jQuery conflict.

How can I solve the issue? Do I need to add any code in that plugin file? If yes, where?

Thanks


Chris Ferdinandi

@Azizul – I’m not at all familiar with that plugin, so I’m afraid I can’t be of much use to you here. I’d recommend opening a ticket with the creator in the support forum. Cheers!

Leave a Reply

Share links, code and more with Markdown. Add an avatar with Gravatar.