jQuery Image Lazy Load Example



If you are using image gallery or your page has more images then sometimes image get start load after the user scroll down to image that increase page load time and that decrease your traffic also.  By using jQuery Image Lazy Load you can reduce the page loading time and the images loads after the page load. In this article I am explaining how to implement the lazy load with a simple example.

In this example I am using Lazy plugin of jQuery you can download this plugin from github.com/eisbehr-/jquery.lazy . You need to include latest jQuery and jQuery Lazy plugin in head of the page or anywhere you want.

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>

Now you need to add a class like “lazy” in img tag and add “data-src” attribute to image those you want to load lazy. like below:

<img class="lazy" data-src="img/sample.jpg" src="" alt="lazy load example" />

Now you need to call the lazy effect after the page load. You should use unique class “lazy” or any other jQuery selector to load images as below:

jQuery(document).ready(function() {
	jQuery("img.lazy").lazy();
});

If you want to show loading image before lazy image you can add loader image in img tag like below:

<img class="lazy" data-src="img/sample.jpg" src="img/preload.gif" alt="lazy load example" />

This Lazy load plugin is work with all browsers. If you want to load images after a delay time you can add a milliseconds time with delay parameter.

jQuery(document).ready(function() {
	jQuery("img.lazy").lazy({
		delay: 2000,
	});
});

You can add show-up-effect for your lazy loading images. You can use ‘effect’ and ‘effectTime’ parameter to set an effect and duration of effect.

jQuery(document).ready(function() {
	jQuery("img.lazy").lazy({
		effect: "fadeIn",
		effectTime: 1000
	});
});

jQuery Lazy plugin allows you to use some callback functions before, on and after loading images. You can use these as you want like below:

jQuery("img.lazy").lazy({
	beforeLoad: function(element) {
		element.removeClass("lazy");
	},
	onLoad: function(element) {
		element.addClass("loading");
	},
	afterLoad: function(element) {
		element.removeClass("loading").addClass("loaded");
	},
	onError: function(element) {
		console.log("image loading error: " + element.attr("src"));
	},
});

Live Demo