# Loading Events
# Loading your HTML Files
There are actually two events that we can use when loading HTML files: load
and DOMContentLoaded
. The load
event tells us when the HTML and everything connected to it has finished loading.
The DOMContentLoaded
event is much more useful, it tells us when all the HTML on the page up to the closing </html>
element has finished being rendered and is ready for us to use.
The load
event can make you wait a really long time to load images, scripts, styles, and fonts. The DOMContentLoaded
event lets us add event listeners to DOM elements and allow the user to start using the behaviours and functionality attached to the page.
//on the document object
document.addEventListener("DOMContentLoaded", function(ev) {
console.log("The DOMContentLoaded event has fired on the document object");
});
//on the window object
window.addEventListener("load", function() {
console.log("The load event has fired on the window object");
});
2
3
4
5
6
7
8
Just be careful about the effect of adding the async
or defer
attributes to your <script>
tags.
# Loading Images, Scripts, and Styles
With images, scripts and styles we don't have a DOMContentLoaded
event because there is no HTML in them. We only have the load
event.
let img = document.createElement("img");
//create a new image element
document.body.appendChild(img);
//add the image to the body
img.addEventListener("load", function(ev) {
console.log("The image has been loaded");
});
//add the listener for the load event to the new <img> element
img.addEventListener("error", function(err) {
console.log("The image failed to load");
});
img.src = "http://picsum.photos/300/300";
//set the src attribute of the image to initiate the load
2
3
4
5
6
7
8
9
10
11
12
13
This same process can be repeated for <img>
, <link>
, and <script>
.
When images are being loaded, they will have several different values for width and height. These have to do with the original size of the image and the rendering size of the image.