Skip to content

Instantly share code, notes, and snippets.

@fredkelly
Created November 26, 2013 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredkelly/7666961 to your computer and use it in GitHub Desktop.
Save fredkelly/7666961 to your computer and use it in GitHub Desktop.
jQuery Retina Replacement
// assumes the following image tag:
// <img src="foo.png" data-2x="foo-hires.png" />
$(document).ready(function () {
// substitute @2x images where available
if (window.isRetina()) {
console.log("loading retina images..");
var replacement;
$('img[data-2x]').each(function(i, img) {
replacement = $(img).clone().attr('src', $(img).data('2x')) || img;
// only replace once the replacement is loaded
replacement.load(function() {
$(img).replaceWith($(this));
});
});
}
});
// Retina detection
window.isRetina = function() {
var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
(min--moz-device-pixel-ratio: 1.5),\
(-o-min-device-pixel-ratio: 3/2),\
(min-resolution: 1.5dppx)";
return window.devicePixelRatio > 1 || (window.matchMedia && window.matchMedia(mediaQuery).matches)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment