CDN JS Scripts Without A Plugin On WordPress

The CDNJS repository (powered by Cloudflare) claims to “host everything” (within reason based on popularity) and has faster response times than either Google or Microsoft’s much more limited content delivery networks (CDNs). There several WordPress plugins which automatically redirect script requests to CDNJS, but for the sake of optimization, there’s no point of adding another plugin when you can make the necessary adjustments in a few seconds.

Open your theme’s functions.php file and paste the following code into it.


add_action('wp_enqueue_scripts', 'CDNJS_scripts');
function CDNJS_scripts() 
{
wp_deregister_script('jquery');
wp_register_script('jquery','https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js');
wp_enqueue_script('jquery');
} 

In the example above, I’ve replaced WordPress’ original JQuery script with the minified copy at CDNJS. If you want to add additional scripts, confirm that they’re available on CDNJS, find the handle on WordPress’ Codex, and follow the pattern below (deregister the script, reregister the script pointing the handle to CDNJS’ path, and then enqueue the handle) as outlined above. Leave a comment if you have questions!

You might also like
6 Comments
  1. kwibbles says

    How do you do this, but with a CSS file?

    1. Rishi says

      Not sure how to do it with a CSS file – why do you ask?

  2. netzc says

    Thanks a lot for this. Have you ever run into version issues with this?

    1. Rishi says

      As in outdated versions? I just manually change the link to the JQuery script (or any script, for that matter) in the code above. Currently rocking JQuery 2.1.3. =)

  3. Sanober Siddiqui says

    what about Microsofts CDN, how to use, i need for my Android APps site name appsandroidapk.com

  4. Paul G. says

    Hey,

    Just letting ya know that I created a plugin dedicated to CDNJS which lets you choose 1 or any of the CDNJS libraries available.

    The WordPRess.org plugin page is: http://wordpress.org/extend/plugins/cdnjs/

    Cheers,
    Paul.

Leave A Reply

Your email address will not be published.