Why and when to use async and defer with your WordPress JavaScript files

Jul 27, 2019

Async and defer are attributes for the HTML script tag that helps you to speed up your page load times by letting your browser to load your JavaScript files in paraller while parsing the HTML tree. They’re used like this:

<script async src="script.js"></script>

or:

<script defer src="script.js"></script>

Flavio Copes wrote a great article on async and defer here. In the article he explains really well how async/defer works and why you should use them. Please read that article first to really understand how they work.

For the context of WordPress my rule of thumb is:

  1. Don’t use async/defer if you need to support older browsers (<IE10), and load your JavaScript files preferrably in wp_footer() like explained here.
  2. Use defer put the script in your wp_header() whenever you can. It works the same way as you would load your JavaScript in wp_footer().
  3. Use async instead of defer if you need to have your JavaScript file executed before parsing all the HTML.

For more information on how to actually use async/defer in WordPress, read this article on wp_enqueue_script() first and then this article on how to add async/defer attributes for scripts loaded with wp_enqueue_script().