getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2018
getButterfly

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.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.


My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.