Learn how to execute JavaScript code as soon as the DOM is ready, without any delay.
To achieve this, you can add an event listener to the document
object for the DOMContentLoaded
event:
document.addEventListener('DOMContentLoaded', (event) => {
// Code to be executed when the event occurs
})
Usually, arrow functions are not used for event callbacks because they don’t have access to the this
keyword. However, in this case, we don’t need to worry about it because this
always refers to the document
object. In other event listeners, it is recommended to use a regular function instead:
document.addEventListener('DOMContentLoaded', function(event) {
// Code to be executed when the event occurs
})
This is especially useful when adding the event listener inside a loop, where it’s uncertain what this
will be when the event is triggered.
In conclusion, adding an event listener to the document
object for the DOMContentLoaded
event allows you to run JavaScript code as soon as the DOM is ready.