How To Lazy Load Images Using jQuery

By | October 27, 2015


How To Lazy Load Images Using jQuery

In this article, we are going to create a simple library which takes a selector (preferably class) and makes the images inside it lazy load. Lazy loading means that the user will request the resources (in this case, images) only when they are needed. In our case, this means when the user scrolls down enough. If the user scrolls to the place where the image is supposed to be, his browser will request the image and it will be displayed to him.

How To Lazy Load Images Using jQuery

If he never scrolls down enough to see most of the images – his browser would have never requested them from our server.

Downlaod and Demo Links are as:-

How To Login With Google Account oAuth in PHPHow To Login With Google Account oAuth in PHP

How to make a lazy loader?

In our <head> tag, we just load jQuery.

In our <body> tag we create a container for the images and give it a class. Inside the container, we place as much images as we need.

We have used the data-src attribute to hold the real src attribute of the image that has to be loaded there. All src attributes point to a small pure black image which serve as a placeholder for the actual images. We also set the width and height attributes to have the dimensions of the real image (the one whose path is store in the data-src attribute). We do not really have to put placeholders with the same image size but we just wanted to make it as smooth as if the image was really there.

Now, let us proceed with the lazyLoader library.

We create an object with an initialize method which takes a CSS-styles selector of the container(s) of the images and calls the revealWhenScrolled  function once when the method is called and hooks up an event listener that will call revealWhenScrolled each time the user scrolls.

The revealWhenScrolled function loops over each image and if the viewport’s vertical position in the document is lower or at the level of the image – it replaces the image’s srcattribute with its data-src attribute.

Finally, we have the isVisible method which checks if the viewport’s vertical position in the document has reached or exceeded the image’s vertical position in the document.

Finally, before we close our <body> tag (placing your scripts after the HTML optimizes the page’s loading speed) we load our lazyLoader library and initialize it:

Now, all the images in the container(s) will load only when the user needs them!

Thanks For Reading :)