Load jQuery CDN With WordPress

CDN

Here is a snippet which allows you to load jQuery from the Google CDN in WordPress.

jQuery is a very popular Javascript framework which can do some very powerful things and makes it very to add Javascript to your page.

One added benefit of jQuery is that Google offer a CDN library you can use on your websites. Using the Google CDN to load jQuery means that you don't need to host this on your website, so when jQuery gets updated you will automatically get the updates and you won't have to change anything on your website. using a CDN means that it will load very quickly as the file will come from a near-by server.

WordPress Wp_register_script Function

Wordpress has a in-built function called wp_register_script which is a safe way of registring javascripts in WordPress for later use.

It will take 5 parameters in the function.

  • Name
  • URL of script
  • Array of any scripts which depend on this script
  • Script version number
  • In the footer. Normally scripts would be added to the head tag but if this parameter is set to true then the script will be loaded to the footer.

This function will register the script but it will not add the script to the page, to do this you need to use the function wp_enqueue_script($registered_name);

WordPress Snippet

Here is the snippet you can use to add jQuery to WordPress, just add the following to your functions.php file.

add_action( 'wp_enqueue_scripts', 'register_jquery' );
function register_jquery() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' ), false, null, true );
    wp_enqueue_script( 'jquery' );
}

This snippet will add this action on the init of the page, first it will deregister any other scripts with the handle jquery, then it will add a new script and finally adding it to the script queue.

Use jQuery UI With WordPress

Wordpress comes with a number of inbuilt javascript library which all developers can access just by calling the wp_enqueue_script using the default handler.

JQuery UI is one of the default libraries available to WordPress which means you can easily load this in your WordPress theme by using the below snippet.

add_action( 'wp_enqueue_scripts', 'load_jquery_ui' );
function load_jquery_ui() {
	wp_enqueue_script('jquery-ui-core');
 	wp_enqueue_script('jquery-ui-datepicker');

	wp_enqueue_style('jquery-style','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
}

View more default WordPress enqueue script handlers on the WordPress codex.

WordPress Default Scripts

Advertise here

Comment