Browser parse html line by line, when it reaches the
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.
Script tag has
async attributes. In fact these modern JS frameworks does that for us automatically
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.
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
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
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.
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