Created
November 13, 2019 18:13
-
-
Save cocodrino/0b8615f1016ee5b555d75aecb88b945b to your computer and use it in GitHub Desktop.
jquery document ready in plain js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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