-->

Saturday, 19 December 2015

Responsive images – how to lazy load and multiserve images

Responsive images – how to lazy load and multiserve images

I recently wrote about how we can prevent browser reflow when serving up flexible images by reserving space for the image so that the page will not reflow when the image is downloaded by the browser. This is done by using a padding-bottom trick that enables us to specify the height as factor of the width. This is a technique that works especially good for slow connections and slow CPU’s.
And this technique makes it much less expensive to insert images with JavaScript. Loading images with JavaScript has been a big no-no because of the reflow and delay it causes. But now that we have eliminated reflow, we can look at loading images this way again. And keep in mind, what we care about is the perceived speed for the user, not how many milliseconds (or seconds…) it actually takes to load it up. And since we now use JavaScript, another door openes up to us: we can choose which image to load based on the screen size and pixel density of the device.
So if we expand on the markup of the previous post, we have now added some image version information to data attributes on the noscript tag. The img inside the noscript tag is used if JavaScript is not enabled.
And working from this it is quite easy to use a script to load the correct image based on screen width of the device. We can also multiply the width with devicePixelRatio so that we get better quality on screens with high pixel density.

The result

  • No reflow
  • Images only load once
  • No .htaccess, PHP or backend hack
  • Small size to small screens
  • Not dependant on cookies
  • Cachable
  • Sensible fallback if JavaScript is turned off
Example on how page size varies: (Taken from the demo site):
  • When getting 240px images: 500kb
  • When getting 320px images: 644kb
  • When getting 480px images: 902kb
  • When getting 640px images: 1.13mb

Demo and code

See the solution in action: http://andmag.se/responsive-images/
The code is available on github: https://github.com/4nd3rs/responsive-images
I would really appreciate (both positive and critical) comments or improvement suggestions to this solution!

UPDATE

Added alt attribute to the image tag for validation and accessibility.
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
 

Delivered by FeedBurner