Created
March 20, 2012 02:07
-
-
Save armandocanals/2130072 to your computer and use it in GitHub Desktop.
Detect retina asset in DOM using javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
orly?