Is it possible to detect support for the DOMContentLoaded
event?
Method's like Kangax's solution here won't work because DOMContentLoaded
is not exposed as a property of any element: Detecting event support without browser sniffing
Is it possible to detect support for the DOMContentLoaded
event?
Method's like Kangax's solution here won't work because DOMContentLoaded
is not exposed as a property of any element: Detecting event support without browser sniffing
Just listen for all three events and the first one triggered wins. If the winner is DOMContentLoaded, it's supported. If it hasn't been triggered by the time one of the other two has been triggered, then it's not supported.
<script>
var hasDOMContentLoaded = false,
ready = false,
readyMethod = null;
// Listen for "DOMContentLoaded"
document.addEventListener("DOMContentLoaded", function(event) {
hasDOMContentLoaded = true;
init("DOMContentLoaded");
});
// Listen for "onreadystatechange"
document.onreadystatechange = function () { init("onreadystatechange"); }
// Listen for "load"
document.addEventListener("load", function(event) { init("load"); });
// Gets called after any one of the above is triggered.
function init(method) {
if(!ready) {
ready = true;
readyMethod = method;
go();
}
}
// Page is ready, time is up.
// Eitehr DOMContentLoaded has been triggered or it never will.
function go() {
console.log("hasDOMContentLoaded: ", hasDOMContentLoaded);
// My initialization code here
}
</script>
Actually & Factually, there is no need for DOMContentLoaded Event. Any script can be used to determine, if the document HTML was completely parsed thanks to the principle of html stream load.
All you have to do, is to put the function (you would otherwise assign to the DOMContentLoaded event) right before the closing tags of your document(s).
It will execute exactly after the last HTML element has been parsed to DOM, and it will execute a bit faster and earlier than the built-in DOMContentLoaded will do.
I found the following explanation about usage of the DOMContentLoaded event from the mozilla developer site very useful. At the end it talks about backwardly compatible ways to do achieve the same thing, which I have extracted here (no surprise it concentrates on IE)...
Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.
© 2022 - 2024 — McMap. All rights reserved.
load
as a fallback. Not really what I'm looking for: github.com/jquery/jquery/blob/master/src/core.js#L813 – UntenableDOMContentLoaded
polyfill, that would be pointless, because those events fire only once. – Untenable