Reputation: 20965
When using jQuery you wait for the DOM to be ready before you start doing stuff. My problem is with images.
Sometimes images take ages to load, and quite frequently not at all. So I want ready() to basically have a timeout. It will wait something like 5 seconds and if these selected images haven't loaded it will run the function.
Is this possible?
Upvotes: 3
Views: 5177
Reputation: 490303
I have a jQuery plugin that waits for images to be downloaded in the context of a selector, and then will fire a callback.
So you can do...
$('body').waitForImages(function() {
// Images have loaded.
});
Upvotes: 0
Reputation: 3798
I think you may have confued document.ready with window.onload
window.onload
this is an event which will fire after the page has finished loading. So this function will not suit you as you will need to wait for all images to have finished downloading (or timing out)
document.ready
this is an event which will fire after the DOM is ready. This is when the browser has actually constructed the page but still may need to grab a few images or flash files. This function will be what you are after, as the DOM is ready to be manipulated before all the images have been downloaded.
You could set up a timer within this function to wait for 5 seconds, and check whether you have downloaded said images
Sample code:
<script>
$(document).ready(function() {
var imagesLoaded = false;
var imagesTimer = setTimeout("alert('images failed to load')", 10000);
$("img.checkme").load(function(){
imagesLoaded = true;
clearTimeout(imagesTimer);
alert('images loaded within 10 seconds')
});
});
</script>
Upvotes: 8
Reputation: 55082
-- Edit: This answer not definitive, only helpful.
Disregard me. This is for images after they've loaded. You want to set a timeout as soon as they are rendered. You'd do something slightly different in this case. On the rendering of each image you'd set a 'startup' timeout, and if the 'load' doesn't cancel that before 5 seconds, you launch whatever you want to do.
There may, however, be an earlier event than load that you can attach to in a general fashion. Not sure.
-- Old:
Indeed sir, I believe you should be able to just attach to the 'img' 'load' event.
Possibly something like:
// not tested, completely made up
$("img").load({ alert("foo"); });
Upvotes: 0