Loading JavaScript is one of the biggest performance bottlenecks. A script tag causes the browser to halt rendering, load a file, and run the code (the script will be executed before parsing is resumed). For slow servers and heavy scripts this means that displaying the webpage will be delayed.

     
 
 

Legend:

HTML Parsing
HTML parsing paused
Script download
Script execution

<script defer>

(deferred execution)

The browser will begin to download the deferred scripts in parallel without stopping page processing (during HTML parsing) and will only execute them after the parser has completed. A positive effect of this attribute is that the DOM will be available for the scripts.

The scripts downloaded with defer are also guaranteed to execute in the order that they appear in the document.

 
 
 

<script async>

(asynchronous execution)

The async is identical to defer, except that the script executes at the first opportunity after download (will pause the HTML parser to execute it when it has finished downloading).

     
 
 

When should I use what?

Typically you want to use async where possible, then defer then no attribute.

Some general rules to follow:

  • 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.

Resources


Categories & Tags


Share