How to Wait for the DOM Ready Event in Plain JavaScript
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:
1 | document.addEventListener('DOMContentLoaded', (event) => { |
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:
1 | document.addEventListener('DOMContentLoaded', function(event) { |
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.
tags: [“JavaScript”, “DOM ready event”, “event listener”]