DEV Community

Farhan Yahya
Farhan Yahya

Posted on • Originally published at

Simple image lazy loading using JQuery

Lazy loading is a technique where images are given a placeholder to be displayed while the actual image is loading in the background. The placeholder gets replaced with the actual image once it's done loading in the background.

Below is a series of fully explained code on how to implement lazy loading

  1. Set the src attribute of your image to be the placeholder image
<img src="placeholder.png">
  1. Give your image tag an attribute ref-src to with the url of the actual image you want to load
<img src="placeholder.png" ref-src="">
  1. write some javascript code to load the image in background and replace the placeholder after image has been loaded
// selecting image element to be lazy loaded
let elem = $("img");
//retrieving url from ref-data attribute
let url = elem.attr("ref-data");
//creating a new image object
let loadingImage = new Image();
//this function is called when the image object
//is done loading it's image
loadingImage.onload = function(){
    //src attribute of elem is being replaced
    //with that of loadingImage because its done loading
    elem.attr("src", url);
//the url from elem has been assigned
//to the new image object for loading 
loadingImage.src = url;

An with this code you've implemented lazy loading. These days most developers ignore the use of spinners as placeholders but rather prefer a grey looking shadow of the image.

Lazy loading all images on your site

To lazy load all images on your website, I have this simple script for you to use. Try understanding the code below because it's very similar to the one above.

let imgs = $("img");
for(let a=0;a<imgs.length;a++){
function loadImage(elem){
  let url = $(elem).attr("ref-src");
  let newImg = new Image();
  newImg.onload = function(){
    console.log("done loading");
    $(elem).attr("src", url);
  newImg.src = url;

Voilà! all images on your site will be lazy loaded but remember to always put your placeholder in the src section and the image you want to load in the ref-src attribute like below

<img src="placeholder here" ref-src="actual image here">

Top comments (0)