Sometimes you may want to know if the DOM is ready to be manipulated. Most of the time you want to run some code only after the DOM is ready to be modified. For that reason for years we used jQuery’s ready() function or some equivalent. Now many have moved on and like to use plain old JavaScript to do everything without libraries. Still, a major benefit of using jQuery(…).ready() is that even if the document (or window‘s) DOMContentLoaded event already fired, the function passed will still be run.

The following will always print to the JS console even if the DOM was fully parsed long ago:

jQuery(function() {
  console.log('The DOM is ready!');

On the other hand, the following will only print to the JS console if the DOM is not fully parsed at the time when the event listener is added:

addEventListener('DOMContentLoaded', function() {
  console.log('The DOM is ready!');

A Simple Solution

The solution to this problem is to test to see if the DOMContentLoaded event would have possibly fired already and then call the function immediately. With this in mind you could use the following code to essentially do the same thing that jQuery does but without needing jQuery:

Here is an example showing how to use this function:

domReady(function() {
  console.log('The DOM is ready!');

If you just want to determine if the DOM is currently ready you can also call it this way:

if (domReady()) {
  console.log('The DOM is ready!');
else {
  console.log('The DOM is not ready yet.');

You can even determine if the code is being called right away from within the function call by doing something like this:

domReady(function(event) {
  console.log('This is ' + (event ? 'a delayed' : 'an immediate') + ' call.');

Legacy Solution

If you would like to use this domReady() function but you need to support legacy browsers such as IE8 or lower then you can use the following definition:

The function is called the same way. The main differences are that if document.addEventListener() doesn’t exist document.attachEvent() is used and the readystatechange event is being targeted instead of the DOMContentLoaded event.

Final Words

Honestly, there are still other reasons why you may decide to use libraries such as jQuery which already provide this functionality. On the other hand, feel free to use this function if you want to minimize your code base. As always, happy coding! šŸ˜Ž

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *