Move JavaScript to the Page Bottom in  WordPress

High Performance Web Sites Book Front CoverSteve Sonders outlines essential rules for speeding up websites on the front-end in his book High Performance Web Sites. He strongly advocates for developers to load JavaScript at the bottom of a page. When a website is loaded in a browser using HTTP, scripts don’t allow parallel downloads. This means that it may take 4 seconds to load a single JS file. Instead it’s best to load your CSS and images first, to avoid a flickr of un-styled content.

It’s easy to do this in WordPress, just add the following to your theme’s functions.php file.

/**
 * Load Enqueued Scripts in the Footer
 *
 * Automatically move JavaScript code to page footer, speeding up page loading time.
 */
function footer_enqueue_scripts() {
   remove_action('wp_head', 'wp_print_scripts');
    remove_action('wp_head', 'wp_print_head_scripts', 9);
    remove_action('wp_head', 'wp_enqueue_scripts', 1);
    add_action('wp_footer', 'wp_print_scripts', 5);
    add_action('wp_footer', 'wp_enqueue_scripts', 5);
    add_action('wp_footer', 'wp_print_head_scripts', 5);
}
add_action('after_setup_theme', 'footer_enqueue_scripts');

I highly recommend Steve’s book. Its straight forward recipe approach is very easy to digest, making it a quick and informative read.

Related Articles

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.