DOM ready functionality using vanilla JavaScript

on in JavaScript DOM
Last modified on

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', () => {
        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', () => {
            if (document.readyState === 'complete') {
                callback();
            }
        });
    }
}

onDOMReady(() => {
    // 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', () => {
    // Document was not ready, place code here
    init();
});

See a JSFiddle demo.

Related posts