Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready() timeout for images

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?

like image 633
Ben Shelock Avatar asked Aug 05 '26 22:08

Ben Shelock


1 Answers

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>
like image 106
wiifm Avatar answered Aug 08 '26 12:08

wiifm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!