Giacomo Balli profile picture
Giacomo Balli
Your Technology Advisor

Over two decades of experience at your service.
I help small business owners make better decisions.

Let's Chat LinkedIn

Swap images for higher resolution

This code sample will allow you to load the view/page super quickly by using low resolution images and then replaces them with their respective high-resolution version asynchronously.

function getHigherResImages(el) {
    var allHighResImages = allEls = [];
    var currentSrc = newSrc = "";
	allEls = el.querySelectorAll("img");
	for (var i = 0; i < allEls.length; i++) {
		allEls[i].style.webkitTransition="-webkit-filter .1s";
		var currentSrc = allEls[i].src;
		var newSrc = currentSrc.replace("=s100", "=s300");
		allHighResImages[i] = new Image();
		allHighResImages[i].imgEl = allEls[i];
		allHighResImages[i].i = i;
		allHighResImages[i].onload = function () {
			var that = this;
			this.imgEl.style.webkitFilter = "blur(10px)";
			setTimeout(function (that) {
				that.imgEl.src = that.src;
				that.imgEl.style.webkitFilter = "blur(0)";
			}, 100, that);
		}
		allHighResImages[i].src = newSrc;
	}
}

Directions:
- create your HTML with low-resolution image files then call getHigherResImages(el);
- el is the parent element containing all the image tags.
- as soon as each higher resolution image is retrieved, it is replaced.

Note:
There is an additional bonus that will apply a blur transition when swapping images.
This snippet depends on using Google Cloud Engine for your image hosting which provides dynamic delivery of images. Make sure to adapt the code to however you wish to define low-res vs high-res images.
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.

Published: Sun, Jan 10 2016 @ 18:51:07
Back to Blog