script element – defer, async, module

 · 1 min read

The HTML <script> element is used to embed or reference executable code; this is typically used to embed or refer to JavaScript code.

Normal script, without async or defer attribute

async

indicating that the browser should, if possible, execute the script asynchronously.

defer

the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Scripts with the defer attribute will execute in the order in which they appear in the document.

How to use

  • If the script is modular and does not rely on any scripts then use async.
  • If the script relies upon or is relied upon by another script then use defer.
  • If the script is small and is relied upon by an async script then use an inline script with no attributes placed above the async scripts.

module

<script type="module" ...></script>is treated as a JavaScript module.

That means we are using ES6 module syntax, import and export. Since there are still many browser’s version that have not been compatible with this feature, we usually utilize babel to transform those parts to ES5 syntax.


  1. script
  2. async-vs-defer