Async and Defer

Page section: playground

This is the original text

If a JS file loads before the HTML on a page and it requires the HTML to run there will be an error.

In this case the file contains the following to change the first paragraph above:

document.getElementById("async-test").innerHTML =
  "Whoo!! This text is loaded from the async-test.js file. ✔✔✔";

When the script is at the bottom of the page all works well. However when placed at the top it doesn’t work and the console logs an error:

Uncaught TypeError: document.getElementById(...) is null

If the file is still above the HTML this can be fixed adding either async or defer to the <script> tag:

<script src="/js/some-js.js" async></script>
<script src="/js/some-js.js" defer></script>

Async and defer are similar in that they both download the HTML and JS files at the same time. However async executes as soon as it is downloaded whereas defer waits until the HTML is fully downloaded and parsed.

Both of these work on this page though defer is usually what you want. With defer both HTML and the JS file download together. The HTML is parsed and the JS is NOT executed until the HTML is parsed. If there are several JS files they will be executed in order of their placement in the file. With defer the smaller JS file is likely to be executed first because it downloads faster. if the script is using the DOM since it waits for the DOM to load first before executing.

(NB. Any scripts loaded from the <head> section using the script frontmatter property are set to defer set now.)

  1. Async vs defer on hashnode provides a great explanation of the differences.
  2. Dev Dreamer vid on async and defer.
  3. Skillforge provides a simple explanation of async.
  4. Gradient borders on Geeks for Geeks.
View contents of: /static/js/async-test.js
document.getElementById("async-test").innerHTML =
  "Whoo!! This is text loaded from the async-test.js file. ✔✔✔";