Skip to content

Instantly share code, notes, and snippets.

@zoe-edwards
Created May 24, 2012 20:43
Show Gist options
  • Save zoe-edwards/2784122 to your computer and use it in GitHub Desktop.
Save zoe-edwards/2784122 to your computer and use it in GitHub Desktop.
Detect high-DPI and use data-hidpi to replace img src
// Are we using a hidpi screen?
var hidpi = window.devicePixelRatio > 1 ? true : false;
if (hidpi) {
// Replace img src with data-hidpi
$('img[data-hidpi]').each(function() {
// If width x height hasn't been set, fill it in
if ($(this).attr('width') == undefined) {
$(this).attr('width', $(this).width());
}
if ($(this).attr('height') == undefined) {
$(this).attr('height', $(this).height());
}
$(this).attr('src', $(this).data('hidpi'));
});
}
@zoe-edwards
Copy link
Author

Create an image like so

<img src="/img/photo.jpg" alt="Photo of a tree">

But add a data-hidpi attribute for the @2x version.

<img src="/img/photo.jpg" alt="Photo of a tree" data-hidpi="/img/photo-highres.jpg">

Then include this script on the page load.

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