Responsive Web Design: Serving Images Efficiently

Delivering images with the right resolution to different client resolutions is a basic of the responsive design of web applications. There are a few ways to achieve that, one of them being using the Media Query of CSS, but in this blog post I am going to present a different approach – Severing images with JavaScript.

I believe I learned this trick from ASPConf. Forgot the name of the speaker, but he is a talented guy!

First, add to the img DOM a separate attribute for the URL of the image for each resolution.


<img regularSrc="LowResImgURL"  retinaSrc="RetinaImgURL" />

Then in $(document).ready, use the following code to serve the correct images to the client, which sets up the src attribute of img DOM with the correct URL at run-time.


$("img").attr("src", fucntion(i, val){
var $this = $(this);
if(isRetina){
return $this.attr("retinaSrc");
}else{
return $this.attt("regularSrc");
}
});