Move JavaScript to the Page Bottom in WordPress

Move enqueued scripts to the footer in WordPress with one function.

  • Loading JavaScript at the bottom of the page speeds up front-end performance, as advocated by Steve Souders in High Performance Web Sites.
  • Scripts block parallel downloads over HTTP, so a single JS file can delay page rendering (e.g., up to 4 seconds).
  • Load CSS and images first to avoid a flash of unstyled content.
  • In WordPress, you can move all enqueued scripts to the footer by adding a short function to your theme's functions.php file.
  • The function removes script-printing actions from wp_head and re-adds them to wp_footer, hooked via after_setup_theme.
  • The author recommends the book for its straightforward, recipe-style approach to web performance.

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.

Resume