Webessence

Responsive IMG loading

A very nice way to serve the correct images based on the device width (the width of the screen). A jQuery example can be seen at http://www.headlondon.com/our-thoughts/technology/posts/creating-responsive-images-using-the-noscript-tag, but I rewrote it to a little standalone script.

The idea is to wrap all IMG tags inside NOSCRIPT tags. So browsers with no javascript will show the default image. Add HTML5 data-attributes to the NOSCRIPT tag that hold the values of the SRC of the images you can serve, based on screen width.

For example:

<noscript data-src-small="cat-small.jpg" data-src-large="cat-large.jpg">
<img src="cat-small.jpg" />
</noscript>

Execute the script after the DOMContentLoaded event (or put it at the end of the document).

(function() {

var src = screen.width < 501 ? "data-src-small" : "data-src-large";

var noscripts = document.getElementsByTagName("noscript");
for (var i = 0; i < noscripts.length; i++) {
var noscript = noscripts[i];
var img = document.createElement("img");
img.setAttribute("src", noscript.getAttribute(src));
noscript.parentNode.replaceChild(img, noscript);
}

}();
Javascript | 2011-10-30 14:05:14 | Comments (1)

Comments

Treadmill Reviews wrote on 2011-11-13 05:31:53

Great! thanks for the share!

Comments are turned off after 90 days.