7537247 7537247 - 10 months ago 40
Javascript Question

Set a condition to swap an image when it takes too long to load

I want to make a condition when an image takes more than 2 seconds to load, swap that image with another one. Now, I have a

function to check the image url, if the url is bad, swap that image. But, what if an image is taking too long to load? Is there a callback I can use when certain images take more than 2 seconds to load?

$('img').on('load', function() {
//do things here
.on('error', function() {
$(this).parent().css('background-image', 'url("/broken-image")');
.each(function() {
if(this.complete) {
console.log('completed here');
}else {
$(this).parent().css('background-image', 'url("/broken-image")');

Answer Source

You can make it work - using the onload function of the image to determine that the image is actually done loading:

var imageElement = document.getElementById("myImage");
var isImageLoaded = false;

imageElement.onload = function() {
    isImageLoaded = true;

setTimeout(function() {
    if (isImageLoaded === false) {
        //2 seconds passed, no dice on the image!
}, 2000);