WordPress Tip : Using CDN hosted Javascript file (Safe Method)

Posted by

So guys, How to use external JavaScript in the wordpress without over loading it ?
By default wordpress uses its own copy of JavaSript (Here – jQuery) for the blog. If you want to use a Externally hosted Copy of javaScript then the best way is to use a function in the function.php

1. So first of all we need to deregister a function which tells wordpress to load the JS hosted on same server. Here is the code which can do this for you :
wp_deregister_script( 'jquery' );

2. The second step is to register CDN hosted JS (Here Google hosted jQuery) to load. The following code will do work
wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');

3. Final step to include the register function to the wp_enqueue_script() hook, this will prevent repeat loading of same script. The code will do trick for you :
wp_enqueue_script( 'jquery' );

The final script will look like this :

<?php
function add_jquery_google() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
    wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts', 'add_jquery_google');
?>

You need to put this code in your theme’s function.php file. You may use same trick to use jQuery hosted on different CDN by just replacing the url with new one.

Leave a Reply

Your email address will not be published. Required fields are marked *