Skip to content

Instantly share code, notes, and snippets.

@cocodrino
Created November 13, 2019 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocodrino/0b8615f1016ee5b555d75aecb88b945b to your computer and use it in GitHub Desktop.
Save cocodrino/0b8615f1016ee5b555d75aecb88b945b to your computer and use it in GitHub Desktop.
jquery document ready in plain js
Document Ready check
This snippet will covers all the browser to check if the DOM is ready.
document.addEventListener("DOMContentLoaded", function() {
console.log('Your document is ready!');
});
Document Ready check for IE8
Offcourse there is IE8, who wants a different way.
document.attachEvent("onreadystatechange", function(){
if (document.readyState === "complete"){
console.log('Your document is ready!');
}
});
Cross-browser Document Ready check
If I would create a small module of it, it would be like this:
var domIsReady = (function(domIsReady) {
var isBrowserIeOrNot = function() {
return (!document.attachEvent || typeof document.attachEvent === "undefined" ? 'not-ie' : 'ie');
}
domIsReady = function(callback) {
if(callback && typeof callback === 'function'){
if(isBrowserIeOrNot() !== 'ie') {
document.addEventListener("DOMContentLoaded", function() {
return callback();
});
} else {
document.attachEvent("onreadystatechange", function() {
if(document.readyState === "complete") {
return callback();
}
});
}
} else {
console.error('The callback is not a function!');
}
}
return domIsReady;
})(domIsReady || {});
source
https://www.competa.com/blog/cross-browser-document-ready-with-vanilla-javascript/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment