How to create lazy loading images?

First of all what is lazy loading images? well in short its an actin that forces your images to stop loading until they are in the screen view, so what you don’t see doesn’t need to load.

This is very useful if you have loads of images stacked under each other on one page, it helps your page to load faster and save bandwidth if your visitor doesn’t want to view the rest of the page for some reason.

Th way this process is achieved is by including jQuery library and calling it in your page, then you will need to change your img src to a placeholder image, don’t worry if doesn’t make any sense now, it will get more clear when you see the codes.

You can view the [live demo] or [download source]

script by Mika Tuupola
we will be using Lazy Load script by Mika Tuupola

you can start by downloading the “Lazy Load – jQuery plugin for lazy loading images” minified version, then you will need a placeholder image to replace your images src if you don’t have any you can download the source from the link above and you will find one in the images folder.

Once you have the jquery.lazyload.min.js and a placeholder image you need to decide how are you going to identify the images that you will target with lazy load, in my demo I’m targeting them by adding a class .lazyLoad to the images. You also need to link to the latest jQuery library so am just linking to the one that is hosted by google cause its widely used by developers so it’s most likely to be cached already by browsers.

This code should go between the tags

Now for everything to make sense check the code below

we add the original image source in data-original and the placeholder image in src , because the place holder image is 1×1 pixel the lazy load will be very small, to avoid that it’ll be a good practice to add the original image size in your attribute like this width=”600″ height=”300″

if you want to support surfers with no JavaScript for some reason you will need to add noscript and the full image tag like this.

the last piece of the code will be to call the lazyload by adding this code somewhere towards the end of your html body.

try it out and let me know how did it work for you …


SEAL 2 by © Robert Sharood | Dreamstime.com

  • kernel

    Hi Karim, thanks a lot for your script it’s very useful. I did as you said but the lazy load is not happening. When I scroll down, all images are already loaded. Could you tell me what am I doing wrong?

    $("img.lazyLoad").lazyload({
    effect: "fadeIn"
    });

    • did you download the “jquery.lazyload.min.js” ?

      can you download the sample from above and see if it’s working on your server?

      • kernel

        yep, I’ve downloaded it and it’s working fine. Thank you!