- The lifecycle of an HTML page has three important events:
DOMContentLoaded
: the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures <img>
and stylesheets may be not yet loaded.
DOMContentLoaded
event: DOM is ready, so the handler can lookup DOM nodes, initialize the interface.
load
: not only HTML is loaded, but also all the external resources: images, styles etc.
load
event: external resources are loaded, so styles are applied, image sizes are known etc.
beforeunload/unload
: the user is leaving the page.
beforeunload
event: the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave.
unload
event: the user almost left, but we still can initiate some operations, such as sending out statistics.
DOMContentLoaded
- The
DOMContentLoaded
event happens on the document
object.
- We must use
addEventListener
to catch it:
document.addEventListener("DOMContentLoaded", ready);
// not "document.onDOMContentLoaded = ..."
DOMContentLoaded
and scripts
- When the browser processes an HTML-document and comes across a
<script>
tag, it needs to execute before continuing building the DOM.
- That’s a precaution, as scripts may want to modify DOM, and even
document.write
into it, so DOMContentLoaded
has to wait.
- So DOMContentLoaded definitely happens after such scripts.
- In the example below, we first see “Library loaded…”, and then “DOM ready!” (all scripts are executed).
<script>
document.addEventListener("DOMContentLoaded", () => {
alert("DOM ready!");
});
</script>
<script src="[<https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js>](<https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js>)"></script>
<script>
alert("Library loaded, inline script executed");
</script>
- Scripts with
async
, defer
or type="module"
don’t block DOMContentLoaded
- Script attributes
async
and defer
, that we’ll cover a bit later, don’t block DOMContentLoaded.
- So here we’re talking about “regular” scripts, like
<script>...</script>
, or <script src="..."></script>
.
DOMContentLoaded and styles
- External style sheets don’t affect DOM, so
DOMContentLoaded
does not wait for them.