Last Updated on

ADVERTISEMENT

When the web browser loads a web page, the HTML parser begins parsing the HTML code and creating the DOM.

Whenever the parser encounters a CSS or JavaScript directive (inline or externally loaded), it gets handed over to the CSS parser or the JavaScript engine as required.

The JavaScript engine loads external JavaScript files and inline code, but does not run the code immediately.

It waits for the HTML and CSS parsing to complete. Once this is done, the JavaScript is executed in the order they were found on the web page: variables and functions are defined, function invocations are executed, event handlers are triggered, etc.

These activities result in the DOM being updated by the JavaScript and is rendered instantly by the browser.

<script>

Let’s start by defining what <script> without any attributes does. The HTML file will be parsed until the script file is hit, at that point parsing will stop and a request will be made to fetch the file (if it’s external). The script will then be executed before parsing is resumed.

<script async>

ADVERTISEMENT

async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has finished downloading.

<script defer>

defer downloads the file during HTML parsing and will only execute it after the parser has completed. defer scripts are also guaranteed to execute in the order that they appear in the document.

When should I use what?

Typically you want to use async where possible, then defer then no attribute. Here are 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.

Compatibility

ADVERTISEMENT

IE9 and below have some pretty bad bugs in their implementation of defer such that the execution order isn’t guaranteed. If you need to support <= IE9 I recommend not using defer at all and include your scripts with no attribute if the execution order matters. Read the specifics here.

ADVERTISEMENT
Categories: WordPress

Jonathan

Jonathan is the owner of Wikicat by Jet Studio Software. He loves technology especially programming and WordPress. Currently studying Visual Basic and how CMS and Google works. Jonathan is an SEO and WordPress expert. He also loves to create high-quality articles based on his real experience and sites for people that don't understand much technology or beginning with it. Helping and providing content for more than 1+ million visitors in the world.

Do NOT follow this link or you will be banned from the site! libero. vel, ut ut suscipit accumsan sit vulputate, commodo quis, Curabitur Aliquam
Share via
Copy link