Skip to content

Instantly share code, notes, and snippets.

@armandocanals
Created March 20, 2012 02:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armandocanals/2130072 to your computer and use it in GitHub Desktop.
Save armandocanals/2130072 to your computer and use it in GitHub Desktop.
Detect retina asset in DOM using javascript
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');
@ggilder
Copy link

ggilder commented Mar 21, 2012

orly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment