Category Archives: lazy loading images

Lazy Loading Images On Web Pages

If you have web pages that contain a lot of images, then the page would be slow to load. If many of the images are below the fold (below the visible region), then it is unnecessary to load them unless the user starts scrolling. I had this exact situation and search for a solution on the web yielded very few. There are lot more articles on pre-loading images than lazy loading.

Ideally when the css property ‘display’ is set to none or the ‘visibility’ is set to hidden, one may expect the browsers to optimize not loading the images. However, that doesn’t seem to be the case.

In mycase, there are multiple tabs and clicking each tab should show the respective section with the images. So, for me scrolling was not the criteria to trigger the image loading, but clicking the tab. So, here is what I had to do.

At the end of the page, just before the </body> have javascript that loops through each of the image that needs to be lazy loaded and change the src attribute of the image element to an image that indicates “loading” or something similar. But before doing this, copy the original src attribute to something else. Then, when the tab is clicked, loop through the set of images applicable to that tab and set the src attribute back to the original src attribute.

What really happens is, when the page first loads, towards the end it executes the javascript by which time, the entire dom with all the images is available. Some of the images might start already loading, but not all. Setting the src attribute to a common loading image is much faster and would prevent loading of any images that haven’t been fetched yet.

Advertisements

2 Comments

Filed under lazy loading images