Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazyloading images - noscript fallback code

I'm loading images on my site using js library jquery lazyload2, to display images I use the code below:

<img class="lazyload img-fluid" src="{{$product->getEncodedThumb()}}"  data-src="{{asset($product->getMainImage())}}" alt="{{$product->name}}">

Everything works fine so far, but I need to make the version of my site for users who don't have javascript enabled, how would I approach this? I could just replace all src tags on lazyloaded images with high quality images, but it would completely miss the point, as it would always download high quality images without lazyloading, how should I redesign my structure to allow for javascript lazyloading & noscript standard loading? Do I need to create completely different layout for noscript users?

like image 671
bestestefan Avatar asked Apr 11 '26 20:04

bestestefan


2 Answers

You can use the new built-in lazy loading in HTML

Just with adding loading="lazy" attribute to your like that:

<img src="https://test.photos/300.jpg" loading="lazy" />

Here you can see browser support:

https://caniuse.com/#feat=loading-lazy-attr

like image 109
Oded BD Avatar answered Apr 14 '26 11:04

Oded BD


Usually img tag is followed by noscript tag with embedded original image, i.e.

/* hide lazyload images for disabled js */
.lazyload-hidden {
    display: none;
}
<img class="lazyload lazyload-hidden img-fluid"
     src="{{$product->getEncodedThumb()}}"
     data-src="{{asset($product->getMainImage())}}"
     alt="{{$product->name}}">
<noscript>
    <img class="img-fluid" src="{{asset($product->getMainImage())}}" alt="{{$product->name}}">
</noscript>
// show lazyload images
$('img[data-src]').removeClass('lazyload-hidden');
like image 38
Denis Ryabov Avatar answered Apr 14 '26 09:04

Denis Ryabov



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!