简体   繁体   English

设置条件以在加载时间太长时交换图像

[英]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. 我想做一个条件,当一张图像需要花费2秒钟以上的时间加载时,将该图像与另一张图像交换。 Now, I have a .on('error') function to check the image url, if the url is bad, swap that image. 现在,我有一个.on('error')函数来检查图像URL,如果URL错误,请交换该图像。 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? 当某些图像加载超过2秒时,是否可以使用回调?

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

You can make it work - using the onload function of the image to determine that the image is actually done loading: 您可以使其工作-使用图像的onload函数确定图像实际上已完成加载:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM