DOM ready functionality using vanilla JavaScript

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

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

Related Articles


Privacy Policy