27 Oct 2015
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 www.codeshare.co.uk in October 2015
//You are free to use, modify and distribute this however you want.
//-----------------------------------------------------------------
var lazyImages = {
init: function () {
revealNextImage();
function replaceThisLazyImage(element, bgImage) {
if (element != null && element != undefined) {
var imagePath = $(element).attr("data-image-path");
var image = new Image();
$(image)
.load(function () {
if(bgImage) {
$(element).css("background-image", "url(" + imagePath + ")");
}
else {
$(element).attr("src", imagePath);
}
$(element).removeClass('lazyimage');
revealNextImage();
})
.attr('src', imagePath)
}
}
function revealNextImage() {
replaceThisLazyImage($('.lazyimage:not(img):first')[0], true);
replaceThisLazyImage($('img.lazyimage:first')[0], false);
}
}
}; $(window).load(lazyImages.init);
</script>
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">
...
</header>
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
Thanks
Paul