Front-end Performance Rule #6: place your JavaScript at the bottom of your page

front-endAccording to the book High Performance Web Sites: Essential Knowledge for Front-End Engineers by Steve Sonders, and at BEST PRACTICES FOR SPEEDING UP YOUR WEB SITE, there is a best practice for boosting front-end performance as follows:

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won’t start any other downloads, even on different hostnames.

So, it should be better to put all javascripts (if possible) at the bottom of the page. How do we apply this to the WordPress website? We then need to do 2 steps as follows:

1. Move all WordPress javascript to the bottom

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

/*
*	Automatically move JavaScript code to page footer, speeding up page loading time.
*/
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);

2. Forcing plugins to put JS at the bottom of the page

Good WordPress plugins will use the wp_enqueue_script function to bundle their js and insert it into the page. The default setting is to place the JavaScript into the head. It’s easy to modify your individual plugins to switch to the bottom of the page.

You’ll need to add a true value to the in_footer variable.

So, normally, in your plugin, you might currently embed a script as follows

wp_enqueue_script('plugin-folder', '/' . PLUGINDIR . '/path/to/your.js', $dependencies);

The above line is creating a link to the needed javascript and passing an array of the dependencies to the wp_enqueue_script function. We want to add a couple variables to this. The final set will be (script, dependencies, version, in_footer). The default value for version is false, so that is what we are adding. You will need to change to as follows

wp_enqueue_script('plugin-folder', '/' . PLUGINDIR . '/path/to/your.js', $dependencies, false, true);

Leave a Reply