Lazy loading images with graceful degradation (JavaScript)

Consider an HTML page with a bunch of tags, each with its own content. I want to convert each tag into a slide into a slide show that is running JavaScript. Each tag can contain images, and they must be lazily loaded into this slide show. I do not want all images to be downloaded immediately.

On the other hand, users who do not have JavaScript and search engines should just see the markup and all the images. How to avoid loading images when JavaScript is enabled and how can I make sure images are loaded when JavaScript is not enabled?

One way is to replace all images with this format:

<img src="" data-src="myimage.png"> 

The problem with this solution is the lack of competent degradation.

Instead, I need to do:

 <img src="myimage.png"> 

The problem is that you cannot prevent the browser from loading all the images on the HTML page. I tried changing the HTML in several ways when the document is ready. For example, replace all src attributes with images with src data, empty the whole body, etc.

Should I sacrifice graceful degradation?

Thanks in advance.

+6
source share
2 answers

The simplest way would be to duplicate image tags enclosed in a <noscript> tag and use their src attribute. Above or below this, you can have the same tags with the user attribute data-src , detect and lazily load them using Javascript.

+4
source

You can enable both versions:

 <img src="" data-src="myimage.png"> <noscript> <img src="myimage.png"> </noscript> 

It may be useful to link individual <img> tags so your JavaScript code can synchronize them. For instance:

 <img src="" class='lazy' data-master="myimage"> <noscript> <img id="myimage" class='super-sized interesting' src="myimage.png"> </noscript> 

Then your JS code can make sure that "scripty" images will display classes, etc., so that you do not have to manually update the two versions (please forgive the jQuery example, of course, you would do it, but you want to):

 $('img.lazy').each(function() { var $lazy = $(this), master = $('#' + $lazy.data('master'))[0]; $lazy.src(master.src); $lazy.className += master.className; // etc }); 
+2
source

Source: https://habr.com/ru/post/901233/


All Articles