Created
November 25, 2012 19:00
-
-
Save rjz/4144806 to your computer and use it in GitHub Desktop.
Scaling images for Retina Displays
This file contains hidden or 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
| /** | |
| * Provide support for retina-specific image elements and background styles | |
| * see: http://blog.rjzaworski.com/2012/11/scaling-images-for-retina-displays/ | |
| */ | |
| (function (doc) { | |
| var opts = { | |
| find: /(.+)(\.\w{3,4})$/, | |
| replace: '$12x$2', | |
| retinaClass: 'retina' | |
| }; | |
| // 1. Test for retina display | |
| var isRetina = function () { | |
| return window.devicePixelRatio > 1; | |
| }; | |
| // 2. Swap images for retina display | |
| var swapImagesForRetina = function () { | |
| var image, | |
| images = doc.getElementsByTagName('img'), | |
| i = images.length; | |
| while (image = images[--i]) { | |
| image2x = image.src.replace(opts.find, opts.replace); | |
| image.src = image2x; | |
| } | |
| }; | |
| // 3. Add "retina" to body class | |
| var addRetinaToBody = function () { | |
| var body = doc.getElementsByTagName('body')[0], | |
| classes = body.className.split(' '); | |
| if (classes.indexOf(opts.retinaClass) == -1) { | |
| classes.push(opts.retinaClass); | |
| body.className = classes.join(' '); | |
| } | |
| }; | |
| if (isRetina()) { | |
| addRetinaToBody(); | |
| swapImagesForRetina(); | |
| } | |
| })(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment