Update: Retina.js 2.0+ now checks that the retina version of your image exists. No need for the below core code change, as this script has been rewritten and now better than it was before. You can also use the data-rjs
data attrubute. Any images that don’t use this attribute will be left alone.
Retina images are a great thing. They are so clear, so crisp. My favorite solution for implementing retina images is retina.js built by imulus. When your users load a page, retina.js will check each image on the page to see if there is a retina version of that image on your server. If a high-resolution variant exists, the script will swap in that image in-place.
The problem is that the script will check every single image that is in your markup. We don’t want this in every case because if every image does not have a retina ready version, then there will be 404 errors and it’s annoying to see in your console! Not all of your images are going to have retina versions for every website. Maybe just a few…
Not all images need a retina version. Here's a better, selective retina.js with no 404 errors. Click To TweetI was working on a website recently where we only had a few images that were going to be retina ready. I changed the script to get an element by its class. Here’s how you do it…
The original retina.js script checks all images in your markup. What we are doing is only checking images with a class name has-retina
and then switching those images out for high resolution ones.
What do you think?
Do you have something to say about this post? Give us your opinion, insight, changes, or alternative way of doing something. We'd love to hear from you!
Yann
Thanks a lot 😀
Kevin Donnigan
You’re welcome!
Evan
Thanks a bunch; what about only running the script on images with a ‘.png’ extension?
anythinggraphic
Hey Evan, sorry for the late reply! Retina.js 2.0+ now supports a data-rjs data attribute so you can manually put that on the images you’d like to swap out.
Mike
This was incredibly helpful for adding backwards compatibility to a large site. Using 2.0 unmodified would have required updating the entire site at once to avoid 404’s. Now I can triage image updates. Once the entire site is updated, I can switch back to the unmodified retina.min.js and then do a site-wide search and replace for the class string to tidy things up. Thank you!
Kevin Donnigan
Hey Mike,
Glad you found this post useful! I appreciate the comment.