无法让LazyLoad和onerror在图像上一起工作 [英] Can't get LazyLoad and onerror to work together on an image

查看:920
本文介绍了无法让LazyLoad和onerror在图像上一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一些图片:

 < img src =http://www.abc/images /abc.jpg/> 

如果图片无法加载(因为 abc.jpg

 < code>< code>不存在,则我会显示一个默认图片。 img src =http://www.abc/images/abc.jpgonerror =this.src ='http://www.abc/images/default.jpg'/> 

如果我添加 LazyLoad 加载到我的图片并加载更轻量级的默认图片,它会变成:

 < ; img 
class =lazy
data-original =http://www.abc/images/abc.jpg
src =http://www.abc/images /graydefault.jpg
onerror =this.src ='http://www.abc/images/default.jpg'/>

现在,当页面加载时,它会在加载实际图像之前首先加载轻量级图像。

但是如果实际的图像不存在会发生什么?轻量级的默认图像将保留在那里,但这不是我想要的:



如何加载我的默认图像( default.jpg )出现错误?



PS:默认图像很重,所以我想避免将其作为默认图像加载。

解决方案

使用lazyload js中的出现选项。在lazy load js中使用下面的代码来显示错误的图片src loading

 出现:function(ele,settings)
{
$(ele).attr(src,$(ele).attr(data-original));
}

当图像在视口中可用时,该函数用data-original代替src。如果未加载数据原始图像url,则加载错误图像。


I have some images on my page:

<img src="http://www.abc/images/abc.jpg" />

If the image can't be loaded (because abc.jpg doesn't exist, for example), then I show a "default" image instead:

<img src="http://www.abc/images/abc.jpg" onerror="this.src='http://www.abc/images/default.jpg'" /> 

If I add LazyLoad to my image and load an even more lightweight default image, it becomes:

<img
    class="lazy"
    data-original="http://www.abc/images/abc.jpg"  
    src="http://www.abc/images/graydefault.jpg"
    onerror="this.src='http://www.abc/images/default.jpg'" /> 

Now, when the page loads, it will first load the lightweight image, before loading the actual image.

But what happens if the actual image doesn't exist? The lightweight default image will stay there, but that's not what I want:

How can I load my default image (default.jpg) on error?

PS: Default image is quite heavy, so I would like to avoid loading it as the default image.

解决方案

Use "appear" option in lazyload js. Use the following code in lazy load js for on-error image src loading

appear: function(ele,settings)
{
    $(ele).attr("src",$(ele).attr("data-original"));
}

This function replaced src by data-original when image is avaible in view port. if data-original image url is not loaded, on-error image is loaded.

这篇关于无法让LazyLoad和onerror在图像上一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆