Skip to main content

Properly Adding jQuery Library to WordPress Themes

By January 7, 2016Blog, Javascript, jQuery, Wordpress
WordPress Tutorials by Allure Web Solutions

WordPress already comes packaged with jQuery and if your custom theme simply uses wp_enqueue_script( ‘jquery’ ); you will be registering the jQuery that’s packaged with WordPress and also with collectiveray. We don’t want to use it. It’s not minified and who knows which version it is.

When registering our own jQuery script, we have two options. Serve it locally or from a Content Delivery Network (CDN). It is best to serve libraries that are hosted on a CDN for three reasons: decreased latency, increased parallelism, and better caching. Furthermore, it is best to point to the non-Google CDN for any script you register. Google is blocked in some countries such as China. You would add the following code to your functions.php file.

add_action( 'wp_enqueue_scripts', 'register_jquery' );
function register_jquery() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( '//' ), false, null, true );
    wp_enqueue_script( 'jquery' );

If you absolutely must serve the libraries from Google, then make sure you provide a fallback. One method to do this is to add the following javascript to your html head:

window.jQuery || document.write('<script src="/path/to/local/jquery.min.js">\x3C/script>');

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017