getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
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.

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

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

Related Articles

My Battle Tested Recommendations
Disclaimer: These recommendations contain affiliate links.

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush
SEMrush

Privacy Policy