Some sites take a long time to load, especially if they have large images to download. 

This post gives you the code to allow your page to load faster, by using lower quality images firstly and then replacing them with the higher quality version after the page has loaded.

Here is the javascript you need. 

<script type="text/javascript">
//Written by Paul Seal 2015. Shared on in October 2015
//You are free to use, modify and distribute this however you want.

var lazyImages = {
init: function () {

function replaceThisLazyImage(element, bgImage) {
if (element != null && element != undefined) {
var imagePath = $(element).attr("data-image-path");
var image = new Image();
.load(function () {
if(bgImage) {
$(element).css("background-image", "url(" + imagePath + ")");
else {
$(element).attr("src", imagePath);
.attr('src', imagePath)

function revealNextImage() {
replaceThisLazyImage($('.lazyimage:not(img):first')[0], true);
replaceThisLazyImage($('img.lazyimage:first')[0], false);
}; $(window).load(lazyImages.init);

My site uses it, so this page is its own example.

You can use it with background images and foreground images.

Here is a sample background image:

<header class="lazyimage" style="background-image: url('/images/smallerimage.jpg');" data-image-path="/images/largerimage.jpg">

Here is a sample foreground image:

<img class="lazyimage" height="185" src="/images/smallerimage.jpg" data-image-path="/images/largerimage.jpg">

You just need to add a class of "lazyimage" and a data-image-path attribute with the path of the higher quality version of the image. Then in the src of the foreground image, or the background-image style you can enter the path of the low quality version of the image. My site uses ImageProcessor.Web so I can generate different quality versions of the image just using the query string. You don't need to have ImageProcessor.Web on your site, you can just have 2 different image paths if you want.

Please share this with your friends or colleagues if you find it useful, and feel free to leave a comment below.

It would be great if you shared your link to your site in the comments below if you implement it on your site



Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

Paul Seal

A .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.



Share Top