Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading of images with graceful degradation (JavaScript)

Tags:

javascript

Consider a HTML page with a bunch of tags each with their own content. I want to transform each tag to a slide in a slideshow powered by JavaScript. Each tag can contain images and they should be lazy loaded in this slideshow. I don't want all images to load at once.

On the other hand, users with no JavaScript enabled and search engines should just the see markup and all the images. How do I avoid images from loading when JavaScript is enabled, and how do I make sure images are loaded when no JavaScript is enabled?

One way would be to replace all images with this format:

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

The problem with that solution is there's no graceful degradation.

Instead, I have to do:

<img src="myimage.png">

The problem with that is that you can't prevent the browser from loading all of the images in the HTML page. I've tried to modify the HTML in several ways when the document is ready. For example, replace all src attributes in images with data-src, empty the entire body and so on.

Do I really have to sacrifice graceful degradation?

Thanks in advance.

like image 675
Morten Avatar asked Nov 10 '11 18:11

Morten


2 Answers

The simplest method might be to duplicate the image tags enclosed in a <noscript> tag and using their src attribute. Above or below that, you could have the same tags with the custom data-src attribute, detect and lazy-load them with Javascript.

like image 190
Steve Lewis Avatar answered Oct 23 '22 05:10

Steve Lewis


You could include both versions:

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

Might be good to relate the separate <img> tags there so that your JavaScript code can keep them in sync. For example:

<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 the "scripty" images pick up the classes etc so that you don't have to manually keep the two versions updated (pardon the jQuery example; of course you'd do this however you want):

$('img.lazy').each(function() {
  var $lazy = $(this),
    master = $('#' + $lazy.data('master'))[0];

    $lazy.src(master.src);
    $lazy.className += master.className;
    // etc
});
like image 26
Pointy Avatar answered Oct 23 '22 04:10

Pointy