Speed
Optimising WordPress JavaScript with defer and async
21 February 2025 · 5 min read
JavaScript is often the biggest brake on WordPress loading speed. By default the browser loads each JavaScript file sequentially — it must download, parse and execute each script before the page renders further. With a website with 20+ scripts this can cost seconds.
At WP Maintainer we install JavaScript optimisation as standard for all our clients. In this article we explain how defer and async work and how to apply them correctly.
The problem: render-blocking JavaScript
When the browser encounters a script tag, it stops rendering until the script is downloaded and executed. This is called "render-blocking" and is one of the biggest causes of slow websites.
The solution: async and defer
HTML offers two attributes to load scripts asynchronously: **Async:** <script src="script.js" async></script> - Script is downloaded in parallel with page rendering - Script is executed immediately after download (can block rendering) - Execution order is not guaranteed - Suitable for: independent scripts, analytics, advertisements
When to use which?
| Situation | Attribute | |---|---| | Script has no dependencies | async | | Script uses DOM (jQuery) | defer | | Script must load first | none (default) | | Inline critical JS | none — place in <head> |
Implementation in WordPress
In WordPress you add async/defer via wp_enqueue_scripts: function add_defer_async($tag, $handle) { if ('my-script' === $handle) { return str_replace('<script ', '<script defer ', $tag); } return $tag; } add_filter('script_loader_tag', 'add_defer_async', 10, 2);
Plugins for automatic optimisation
Testing after implementation
Always test thoroughly after changes: 1. Check whether all functionality works (forms, sliders, menus) 2. Test on mobile devices 3. Check the console for error messages 4. Measure the difference with PageSpeed Insights
WP Maintainer optimisation
We optimise JavaScript loading order as part of our maintenance plan. We test which scripts can use async/defer, implement this carefully and check whether everything keeps working. This is how we extract the maximum speed gain from your website.