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");
}
});

Easily display loading animation with jQuery

Giving users a proper feedback is one of the most important design items toward a good user experience. Showing the user a loading animation such as a loader or spinner after a request is submitted is something we see quite often. So how to add a loading animation to your own web site? Hopefully the following tutorial can give you a jump start.

First, find a loading animation that suits your need. This Ajax loading GIF generator is a good option to find a decent GIF image. Or you could go for a pure JS and CSS loading animation like the ones in the Collection by Tim Holman.

Then put the animation on the same page where you want to show it and hide it.

Lastly, use the following codes that show the animation whenever an ajax call has been initiated and hide it when finished.


$(document).ajaxStart(function () {
 $YourLoadingAnimation.show();
 }).ajaxStop(function () {
 $YourLoadingAnimation.hide();
 });

References:

jQuery API – ajaxStop

jQuery API – ajaxStart