Moving jQuery to the footer in WordPress to eliminate render-blocking resources

Move jQuery to the footer in WordPress

If you’ve ever used Google PageSpeed Insights to analyze your site’s speed then you’ve probably seen an advice to eliminate render-blocking resources. One of the reason why you might see this advice is because of jQuery which comes from WordPress core. In this article, we would like to show you how to move jQuery to the footer to eliminate render-blocking resources in your WordPress site.

By default, WordPress automatically loads a jquery.js file along with a jquery-migrate.min.js file and puts these files in the head of your site. In just about every case, it is a good idea to place all your scripts at the end of the page to prevent the whole page being delayed.

Why does WordPress load jQuery in the header?

This practice of inserting scripts at the bottom of the page has appeared only a few years ago. WordPress has started to load these files in the header before this practice became popular on the web. There are many plugins and themes that use jQuery as a dependency for some additional functionality.

As a result, they expect these jQuery files to be in the head of your site. If the theme’s or/and plugin’s scripts will be putted before jQuery then they simply won’t work. Also, it can cause other JavaScript issues on the site. So, it is very important to check your theme and plugins before moving jQuery to the footer.

For example, we have rewritten JavaScript functionality of our premium professional themes last year, so they no longer use jQuery. If you do not know how to check your theme regarding jQuery dependency then contact the author(s) of your plugin(s) and the theme for more information about jQuery dependency.

How to move jQuery script to the footer?

If you’ve confirmed that moving jQuery from the header to the footer in your site will not cause any issues then we are ready to enqueue jQuery at the bottom of the page. We are going to use a small code snippet to move jQuery to the footer in your WordPress site:

function mytheme_move_jquery_to_footer() {
    wp_scripts()->add_data( 'jquery', 'group', 1 );
    wp_scripts()->add_data( 'jquery-core', 'group', 1 );
    wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
}
add_action( 'wp_enqueue_scripts', 'mytheme_move_jquery_to_footer' );

There are several ways to include this code on your site. You can either use a functions.php file located in your child theme, or you can use a special plugin that allows to add code snippets. For example, you can use Code Snippets which is located in a WordPress plugin directory.

Note, there might be some plugins that can override your rule of moving jQuery to the footer section.

Posted in Guides, WordPress

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.