Introduction
There are three significant events in the lifecycle of an HTML page:
- DOMContentLoaded: the browser has fully loaded HTML, and the DOM tree has been constructed, but external resources such as images and stylesheets may not have yet loaded.
- load: HTML and all external resources such as graphics and styles are loaded.
- beforeunload/unload: the user is about to leave the page.
Each incident has the potential to be beneficial:
- DOMContentLoaded event: The handler can find DOM nodes and initialise the interface now that the DOM is ready.
- load event: External resources are loaded, allowing styles to be applied and picture sizes to be determined, among other things.
- beforeunload event: The user is about to leave; thus, we can see if they saved their modifications and inquire if they want to go.
- unload: Although the user has almost left, we can still perform some actions, such as sending out statistics.
Let’s look into the specifics of these events.
DOMContentLoaded
The DOMContentLoaded event happens on the document object. To capture it, we’ll need to use addEventListener.
As demonstrated in the example, when the document is loaded, the DOMContentLoaded handler is called, and it can view all of the elements, including the <img> below.
<script>
function ready() {
alert('DOM is ready');
console.log('Logo has been loaded!!!');
}
document.addEventListener("DOMContentLoaded", ready);
</script>
<img id="img" src="logo.png">
It does not, however, wait for the image to load. As a result, the alert displays zero sizes.
The DOMContentLoaded event appears to be pretty straightforward at first glance. The DOM tree is complete – now for the event. Albeit, There are a few quirks.
Scripts
When a browser encounters a <script> tag in an HTML document, it must execute it before proceeding to build the DOM. That’s a precaution, as scripts may wish to edit DOM and even document.write into it. Thus DOMContentLoaded has to wait.
As a result, DOMContentLoaded occurs after such scripts:
<script>
document.addEventListener("DOMContentLoaded", () => {
alert("DOM is ready!");
});
</script>
<script src="demo.js"></script>
<script>
alert("Library is loaded and Inline Script has been executed");
</script>
Styles
DOMContentLoaded does not wait for external style sheets because they do not affect the DOM.
However, there is a glitch. If we have a script after the style, then the script must wait till the stylesheet loads:
<link type="text/css" rel="stylesheet" href="style.css">
<script>
alert(getComputedStyle(document.body).marginTop);
</script>
This is because, in some cases, such as in the example above, the script may need to obtain coordinates and other style-dependent properties of elements. Thus, it must wait for styles to load.
In the same way that DOMContentLoaded waits for scripts, it now also waits for styles.