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
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A different event, load , should be used only to detect a fully-loaded page.
If you want to know "exactly" if DOMContentLoaded was fired, you could use a boolean flag like this: var loaded=false; document. addEventListener('DOMContentLoaded',function(){ loaded=true; ... }
The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images.
DOMContentLoaded and styles External style sheets don't affect DOM, so DOMContentLoaded does not wait for them. The reason for this is that the script may want to get coordinates and other style-dependent properties of elements, like in the example above.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With