Created
November 26, 2013 21:53
-
-
Save fredkelly/7666961 to your computer and use it in GitHub Desktop.
jQuery Retina Replacement
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
// 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