Categories
Opinions

About JavaScript Script tag execution order

Browser parse html line by line, when it reaches the script tag it stops rendering, at that moment, downloads the JavaScript, parses it, executes and continues the html parsing.

This behavior, scratch that, this might not be intended behavior that you want to see. Because the waiting period of JS downloading, execution might be in milliseconds or seconds or minutes.

That’s way the old hack was to always put your scripts at the bottom of html document.

Modern ways

Script tag has defer and async attributes. In fact these modern JS frameworks does that for us automatically

Defer

If you’re not sure what to chose, then defer is good option. It tells the browser that “defer the execution of this script, until entire html file is parsed” and then download and execute the script.

This options will follow the order of scripts in HTML.

Async

It tells the Browser that, only download this script and continue doing HTML parsing, but when the script is downloaded than pause HTML parsing and execute this script. And resume the HTML parsing.

This option is good choice for small scripts like analytics or a script that pings server and so on.

Most of the time, we need to work with the page, if we use defer in our script, that i can safely start dom manipulation like

document.querySelector('nav')

We can do that, but it is not good practice, in theory it might happen, some browser are still working in creation of DOM, parsing is finished but for some reason dom structure in memory is not finished. that’s why window object has event

DOMContentLoaded vs load

DOMContentLoaded

Dom object is ready for us in memory to manipulate,

To work with the DOM, it’s better to wait for event, before this event the DOM element might not be available.

load event:

This is an event from old days, load waits for everything in page to be loaded and parsed like scripts, images, videos. when everything is finished. So you have lost the opportunity provided by this wait time to manipulate the dom.

DOMContentLoaded doesn’t guarantees that page is rendered, appeared on the screen

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.