DOM ready functionality using vanilla JavaScript

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

With my recent crusade against jQuery, I needed a reliable way of checking for DOM ready. As window.onload would not satisfy all scenarios, I came up with another solution.

The first version uses a procedural function, while the second one uses a callback function.

if (document.readyState !== 'loading') {
    // Document is already ready, just execute code here
    init();
} else if (document.addEventListener) {
    //document.addEventListener("DOMContentLoaded", init);
    document.addEventListener('DOMContentLoaded', function() {
        // Document was not ready, place code here
        init();
    });
} else {
    document.attachEvent('onreadystatechange', function() {
        if (document.readyState !== 'loading') {
            init();
        }
    });
}

function init() {
    // Do stuff
}

Second:

function onDOMReady(callback) {
    if (document.readyState !== 'loading') {
        callback();
    } else if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', callback);
    } else { // IE <= 8
        document.attachEvent('onreadystatechange', function() {
            if (document.readyState === 'complete') {
                callback();
            }
        });
    }
}

onDOMReady(function() {
    // do something
});

In the first example, note the alternative way of calling the init() function:
I would go with the second one, as it’s more readable.

document.addEventListener("DOMContentLoaded", init);

vs

document.addEventListener('DOMContentLoaded', function() {
    // Document was not ready, place code here
    init();
});

See a JSFiddle demo.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Thursday, June 21, 2018 in Blog, JavaScript. Last modified on Wednesday, July 4, 2018.

Contribute!

Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy