Add Async & Defer Attributes in WordPress Scripts

Add Async & Defer Attributes in WordPress Scripts

WordPress loads lots of JavaScript files and have a biggest impact in our website performance. Most of the time <script> tag causes our browser to stop loading file or blocked from displaying so JavaScript can start to write the page. Loading large libraries would be surely painful. This is why these scripts are referred to as render blocking JavaScript.

To resolve this issue is to move all your scripts to the footer of the page, but there is some events its not possible, the other option is to add “defer” and “async” attribute to your script tags.

HTML5 introduce the Async attribute which will help to load script asynchronous, but older browsers does not support it, so you can use Defer attribute in older browsers.

What is Async?

This execute the script when when finish downloading and does not disrupt HTML parsing.

Example usage in HTML.


What is Defer?

This delays the execution of the script until the HTML parser has finished.

Example usage in HTML.


Here is a code snippet to add the async and defer attributes to all script elements in your WordPress site. Go to your theme folder and put it on your functions.php file.


Both these attributes are well supported in all modern browsers including Firefox, Chrome, Opera and Edge.