I have a script that is being inserted dynamically via another script. The code in that script is wrapped inside the $(window).load()
event because it requires the images on the page to have all loaded. In some browsers it works fine, but in others it seems not to fire because the page has already finished loading by the time the code is run.
Is there any way to check and see whether the page has already finished loading - either via jQuery or JavaScript? (including images)
In this situation, I don't have access to the onload
event of the original document (aside from altering it via the loaded script - but that would seem to present the same problem).
Any ideas/solutions/advice would be greatly appreciated!
You can check the document. readyState property. From MDN: Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.
The general idea is that window. onload fires when the document's window is ready for presentation and document. onload fires when the DOM tree (built from the markup code within the document) is completed.
The $(document). ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded.
You could try setting up a handler that's invoked via a timeout that will check the images to see if their properties are available. Clear the timer in the load
event handler so if the load event occurs first, the timer won't fire. If the properties aren't available, then the load event hasn't fired yet and you know that your handler will eventually be invoked. If they are, then you know that the load event occurred before your handler was set and you can simply proceed.
Pseudocode
var timer = null;
$(function() {
$(window).load( function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
process();
});
timer = setTimeout( function() {
if (checkAvailable())
process();
}
}, 10*1000 ); // waits 10 seconds before checking
});
function checkAvailable()
{
var available = true;
$('img').each( function() {
try {
if (this.height == 0) {
available = false;
return false;
}
}
catch (e) {
available = false;
return false;
}
});
return available;
}
function process() {
... do the real work here
}
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