public
Last active

Detect retina asset in DOM using javascript

  • Download Gist
retina_detect
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
function retina(selector) {
var element = document.querySelector(selector);
var images = Array.prototype.slice.apply(element.getElementsByTagName("img"));
var extension = "_2x";
if (window.devicePixelRatio === 2) {
images.forEach(function(img, idx) {
var src = img.getAttribute('src');
img.setAttribute('src', src.replace(/(\.jpg|\.png|\.gif)$/, extension + '$&'));
img.onerror = function(evt) {
img.setAttribute('src', src);
};
});
};
}
retina('#element');

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.