Responsive Lazy Loading

Lazy loading, a web development that holds off on loading images until they are needed, is a great way to speed up your website. When the user doesn’t have to wait for all of your images to load, they get a quicker response time and an improved experience.

There are lots of lazy loading libraries out there, but I couldn’t find one that went the extra mile and also downsized images so that they were no bigger than they needed to be.

Libraries like Bootstrap are great at making sure images fit into the space required of them with classes like img-fluid. But, a 1024×1024 image is still a 1024×1024 image even if it is being squeezed down to 300×300 by the browser. The net effect of this is that the user is downloading a much bigger file than they need, wasting bandwidth and time.

The solution? Responsive sized Lazy Loading.

Glazy: A Responsive Lazy Loading Function

function glazyload(){
  $('img.glazy').each(function(){
    img = '';
    if($(this).data('img')){
      img = $(this).data('img').toString().trim();
    }
    if(img == ''){
      img = 'placeholder.jpg';
    }

    width = $(this).parent().width();
    minwidth = $(this).data('imgminwidth');

    if(width == 0){ width = $(this).parent().parent().width(); }
    if(width < minwidth){ width = minwidth; }
    if(width == 0){ width = 600; }

    $(this).attr('src','image.php?imagefile=' + img + '&resizetoWidth=' + width);
  });
}

$(document).ready(function(){
  // setTimeout(function(){glazyload();},2000);
  glazyload();
});

How does it work?

Images should initially be set up with a blank src parameter (or pointed to a very small placeholder image) and the class “glazy”. The path to the original version of the image should be data in the data-img parameter. An optional data-imgminwidth can be supplied to provide a minimum width for the image should glazy have a problem working out how big the image should be.

<img src="uploads/placeholder.gif" data-src='uploads/mypic.jpg" data-imgminwidth="300" class="glazy">

When the webpage has been loaded, the glazy() functional will be called automatically. This function will:

  1. Find every image with the class “glazy”
  2. Work out how large this image should be based the width of its parent.
  3. If the parent is an <a> tag, or something else without a width, the width of the grandparent element will be used.
  4. If no width is found, the width will be set to the minimum width specified for the image or, failing that, a fallback hardcoded into the function
  5. Replace the src parameter of the img tag in question with a pointer to an image resizing script, passing the source image and a target width

I use my own homebrewed image.php file to do resizing, you should be able to do just as well with something like TimThumb on PHP or whatever the equivalent is for your platform.

Leave a Reply

Your email address will not be published. Required fields are marked *