Last Updated: May 31, 2021
·
454
· paul-ngc

Easy Retina images script

An easy script for jquery to let images src changes automatically when the device the website is viewed with has a Retina display:

if (window.devicePixelRatio == 2) {

var images = $("img.your-img-class");

// loop through the images and make them hi-res
for(var i = 0; i < images.length; i++) {

    // create new image name
    var imageType = images[i].src.substr(-4);
    var imageName = images[i].src.substr(0, images[i].src.length - 4);
    imageName += "@2x" + imageType;

    //rename image
    images[i].src = imageName;
}
}