Today I’m going to talk a bit about the picture element. and how said element can be used in your future project.
The <picture> element is a relatively new element. And the support across major browsers is pretty good. Safari on IOS 9.3 and the latest version of android both have support for <picture>. Unfortunately IE 11 and below do not support it. But for that we can use a fallback which I will talk about later also.
So, what is it used for?
The <picture> element let’s you make responsive images. Yes that’s right! No more having a bit header image for your client which has a size of: 1440 x 400 for example. Now you can actually make sure that you load different sizes for different resolutions. This makes the loading time on a portable device considerably faster which means your visitors (and thus your client) are happier.
How does this work in general
First off, let’s explain how this works with normal images:
<picture> <source srcset="big-logo.png" media="(min-width: 600px)" /> <img src="small-logo.png" alt="logo" /> </picture>
The code above shows a <picture> element and within are a source element with and and a default <img/> element. The <img /> element is your default which the picture element loads when you don’t have a media set or when the picture element is unsupported by your browser.
Then there is the source-element. It uses the srcset and media attributes. Srcset is used to enter a smaller image source. And in media you can add a media query just like in CSS. So in the example we query ‘big-logo.png’ only if the screen is wider then 600 pixels “big-logo.png”. If the screen is less then 600 pixels wide the default <img /> gets loaded.
Of course you can add multiple sources with all different mediaqueries. And then according to your input it will display the other sizes.
Creating a fallback for old browsers
This library helps you check for browser support.
Since Modernizr doesn’t have a test for the <picture> element, we wrote one:
window.Modernizr.addTest('picture', 'HTMLPictureElement' in window ); window.Modernizr.addTest('srcset', 'srcset' in document.createElement('img'));
Now that we have a test we can do the following:
//add picturefill if Modernizr's picture-test fails: if( window.Modernizr.picture === false ) require( ['picturefill'] );
This concludes my blog about the <picture> element. Finally, here’s a working module for you all: