Briefly
The event load
occurs when both the HTML page is loaded (this is handled by the DOM
event) and all resources for displaying it to the user are ready: styles, images, and others.
How to write
You can subscribe to the window
object:
window.addEventListener('load', function () { console.log('The page is ready!')})
window.addEventListener('load', function () { console.log('The page is ready!') })
Or catch the event on elements that have a loading resource:
const img = document.getElementById('img')img.addEventListener('load', function () { alert('Here comes the picture')})
const img = document.getElementById('img') img.addEventListener('load', function () { alert('Here comes the picture') })
How to understand
The load
event guarantees that the browser has rendered the page completely: all styles and images are ready, the sizes of elements on the page are calculated correctly and are available. The preceding load
event DOM
does not provide such guarantees. The same goes for separate elements on the page. If load
has occurred, it means the element has fully loaded.
Try opening a new page with the button in the demo:
window.addEventListener('load', function () { alert('Whoa! The page has fully loaded, so the styles are pleasing to the eye!')})
window.addEventListener('load', function () { alert('Whoa! The page has fully loaded, so the styles are pleasing to the eye!') })
In practice
Advice 1
🛠 More often use DOM
.
🛠 The load
event is used when the code works with styles and other display parameters. Such code is needed rarely, which is why the event is not often used.