LouisWhit
8/7/2018 - 7:05 PM

Retina Images @2x - Jquery Ajax Auto Image Swap

Use jquery to check all the images on a page for their @2x named big brothers/sisters. If they exist swap out the larger retina images with the smaller versions to give a final crisp image. The if check for "assets/" ensures the system only checks for local image files.

jQuery(window).load(function() {
	$(".mainContent img").each(function(index) {
		var el = $(this);
		var src = el.attr("src");
		src = src.split(".");
		if (src[0].indexOf("assets/") > 0){
		  src = src[0] + "@2x." + src[1];
		  $.ajax({
	         type: "HEAD",
	         async: true,
	         url: src,
	     }).done(function(message,text,jqXHR){
	         el.attr("src",src);
	         // console.log("Upgraded: "+src);
	     });
		}
	});
});