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.


Filed under lazy loading images

2 responses to “Lazy Loading Images On Web Pages

  1. needs to load more than 400 dvd images on the front page. So, a similar approach is used to load the images on demand. Clicking a decade link loads the dvd images of all the Oscar nominations for that decade.

  2. Lazy loading of images is a good idea. This seems to be an overly complex solution….

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s