views:

296

answers:

2

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?

A: 

-- 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"); });
Noon Silk
+4  A: 

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

further reading

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>
wiifm
I would use the window.onload event for clearing the timeout. You want to know if all the images finish loading before the timeout, and window.onload will fire when all the images have finished loading.
Joel Mueller