Change the Source of jQuery in WordPress

Posted July 5, 2012 by Chris Luongo in WordPress

WordPress-logo

Many reasons exist for picking a specific source for jQuery. One frequent example is the ability to host jQuery in a cloud or cdn environment. Insert the following function to pick where jQuery in hosted in your WordPress installation.

For many reasons, the fact that WP now comes preloaded with the entire jQuery library is awesome. However, many developers will feel more comfortable choosing where the library resides. Here is how to use your own hosted jQuery library instead of the default WP one.

We are going to edit the functions.php file through the WP Admin. Alternatively, you can perform this by simply editing the functions.php file in your current theme.

1 Navigate to Appearance – Editor

Wordpres Appearance Editor

2 On the right will be a list of all the current files in your theme being used on WordPress. Located your functions.php file and click on it to open it.

Wordpress Functions.php editor

3 We need to take off the current jQuery that is registered with WordPress, register ours, then re-add the file to the theme. So simply cut and paste the code into your WordPress functions.php file below:


function add_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://code.jquery.com/jquery-1.7.1.min.js');
wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts', 'add_scripts');

Please note that in the 3rd line of code we use the jquery.com hosted library. You can change that link with an exact link to wherever you have it hosted.

4 Hit update file to save the changes.

5Now you have your own hosted solution of the jQuery library in WP. This allows you to run nonstandard versions of jQuery or host the library in a cdn to improve your load times.

 

About Chris Luongo

Chris is a self-taught web designer and developer out of Atlanta, GA. This geek enjoys coffee, cold brews, bike riding, and twisting any form of tech into submission.
View more articles by Chris Luongo

The Conversation

Follow the reactions below and share your own thoughts.

  • i prefer this way:
    if( !is_admin()):
    wp_deregister_script(‘jquery’);
    $ver = ‘1.7.2’;
    $url = sprintf( ‘https://ajax.googleapis.com/ajax/libs/jquery/%1$s/jquery.min.js’,
    $ver); // the URL to check against
    if(@fopen($url,’r’) === false) // test if the URL exists
    $url = sprintf( ‘%1$s/js/jquery-%2$s.min.js’,
    get_template_directory_uri(),
    $ver);
    wp_register_script( ‘jquery’,
    $url,
    array(),
    $ver,
    true);
    unset($ver,$url);
    endif;
    Best regards
    S.