There are two types of Loading events:
- DOMContentLoaded
- Loaded
DOMEContentLoaded:
It happens after index.html has been parsed.
<!DOCTYPE html> <html> <head> <title>Ultimate Courses</title> <link rel="shortcut icon" href="favicon.png"></head> <body> <header class="header"> <div class="logo"> <div class="logo-ultimate"></div> <p class="logo-name">Ultimate Courses<span>™</span></p> </div> </header> <script> <div id="app"></div> <script type="text/javascript" src="main.bundle.js" async></script></body> </html>
Which means it read thought the whole <html></html> tag. But it will not wait for css / images/ javascript files to load.
Loaded
"Loaded" event fire when all the css / javascripts get loaded. So it happens after "DOMContentLoaded" event.
"async" keyword
Notice that in the above code example, we have script with async
<script type="text/javascript" src="main.js" async></script></body>
Because it takes time to wait Javascript finishing loaded. Using 'async' keywrod means that "Continue parsing the rest of html code, don't wait for this Javascript file".
So what's the impact?
Let's have a look code inside main.js:
document.addEventListener("DOMContentLoaded", () => { alert("DOMContentLoaded"); });
So when you run the html, will you see the alert dialog?
.
.
.
.
.
Answer: Nope.
Because it takes time to load main.js file, and it is loaded async. Therefore by the time main.js finish loading, all the html have been parsed, so "DOMContentLoaded" happend before our listener code get chance to run.
Also when using "async" and js files get loaded, then browser will stop parsing html and instead it will start parsing the javascript file.
html
|
div
|
script file async. --> start loading
div |
| loaded
-(stop)- |
-(stop)- parsing js
-(stop)- |
continue <---- finsihed
If you want to see the alert dialog you can just remove "async":
<script type="text/javascript" src="main.js"></script>
Then browser will wait main.js load to be finished and Javascript file to be parsed. And it will block all the rendering, it might not be a user friendly approach.
"defer" keyword
It will load script / css async.. But before "DOMContentLoaded" event, it will parse the javascript /css file.
<script type="text/javascript" src="main.js" defer></script>
Question: will you see the alert dialog this time?
.
.
.
.
Answer: Yes.
Because it execute the js file before DOMContentLoaded event. And it will block the rendering.