Ahtesham ul haq
Ahtesham ul haq

Reputation: 339

Can't get LazyLoad and onerror to work together on an image

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.

Upvotes: 2

Views: 3852

Answers (1)

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.

Upvotes: 1

Related Questions