Overview
This article provides information about how to optimize JavaScript to improve your WordPress site's performance.
JavaScript optimization tips
JavaScript can improve your site, though it can also cause pages to load more slowly if not properly implemented. These sections describe several ways to optimize JavaScript on your WordPress site.
Using an online tool to analyze your site
You can use an online tool to analyze your website. These tools provide a breakdown of what may be causing your site to load slower than expected and insights to troubleshoot further.
JavaScript render-blocking
JavaScript is rendered as the browser reads the webpage (top-down). When a JavaScript file is encountered, the browser stops rendering the page until the JavaScript file has been fully read. This is referred to as JavaScript render-blocking and can cause a delay as the page loads.
Using remote JavaScript
Instead of inserting remote JavaScript towards the top of your page, you can instead add it right before the </body> tag in your theme. Due to the way the load order is handled in the browser, this allows your content to start rendering and display on the page before waiting for remote files (which load first if they are in the header). There are also a few plugins available that can do this for you.
Using local JavaScript
Placing the local JavaScript code at the bottom of the page can also speed up load time. You can edit your theme by migrating any local JavaScript code from header.php to footer.php.
Compressing JavaScript code
While mod_deflate compresses JavaScript code, you can decrease the resource usage even further by pre-caching the compression. This requires saving a gzip copy of your theme's JavaScript code in the same directory as your current files.
Some themes attempt to compress JavaScript and CSS by adding a .php to the end of the file name. This actually processes the file through PHP unnecessarily and can cause significant overhead. If you notice your theme doing this, you can modify it by using the gzip method described below.
- SSH into your web server.
- Navigate to the wp-content/themes/ directory.
- When you find the JavaScript code for your site, run the following command. Make sure to replace javascript.js with the actual filename you wish to compress:
[server]$ gzip javascript.js
- Repeat the process for all of your files. A compressed version of your .js files is created.
The benefit of this is that once you complete these steps, no further action is required.
See also
DreamHost links