How Do I Fire An Event When Document Readystate Is Complete
I want to fire and event when the DOM has completely loaded. I checked out document.readyState but it's not an event. I want to fire it when the readyState is complete. How do I do
Solution 1:
Some easy googling point me to this code:
// alternative to DOMContentLoadeddocument.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
And to this link
Solution 2:
Handle the window.load
event.
This will only fire when all external resources (including images) have loaded.
Solution 3:
Taken from another post, however, you could do it like this:
var alreadyrunflag = 0; //flag to indicate whether target function has already been runif (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
alreadyrunflag = 1;
// perform what you need to
}, false);
} elseif (document.all && !window.opera) {
var contentloadtag = document.getElementById("contentloadtag");
contentloadtag.onreadystatechange = function() {
if (this.readyState == "complete") {
alreadyrunflag = 1;
// perform what you need to
}
}
}
//fallbackwindow.onload = function() {
setTimeout(function() {
if (!alreadyrunflag) {
// perform what you need to
}
}, 0);
}
This checks that the DOM is fully loaded, however, if it isn't, it falls back to onload
. You can obviously manipulate this though.
Also, if JQuery is an option, you can achieve the same effect by using just one simple function:
$(document).ready(function() {
// Handler for .ready() called.
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
Solution 4:
For anyone already using the jQuery library the ready function can be used to handle this.
Otherwise the solution from @Neal will achieve the same functionality without needing to add an additional dependency.
Post a Comment for "How Do I Fire An Event When Document Readystate Is Complete"