A Responsive Images approach that you can use today, that mimics the proposed picture element using
divs, for safety sake.
- Author: Scott Jehl (c) 2012
- License: MIT/GPLv2
Demo URL: http://scottjehl.github.com/picturefill/
Note: Picturefill works best in browsers that support CSS3 media queries. It includes (externally) the matchMedia polyfill which makes matchMedia work in
media-query-supporting browsers that don't have
matchMedia, or at least allows media types to be tested in most any browser.
matchMedia and the
matchMedia polyfill are not required for
picturefill to work, but they are required to support the
media attributes on
Size and delivery
picturefill.js compresses to around 498bytes (~0.5kb), after minify and gzip. To minify, you might try these online tools: [Uglify]:(http://marijnhaverbeke.nl/uglifyjs), [Yahoo Compressor]:(http://refresh-sf.com/yui/), or Closure Compiler. Serve with gzip compression.
Markup pattern and explanation
Mark up your responsive images like this. The data-media attribute on each div[data-src] element accepts and and all CSS3 media queries, such as
max width, or even
min-device-pixel-ratio for HD (retina) displays.
<div data-picture data-alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia"> <div data-src="small.jpg"></div> <div data-src="medium.jpg" data-media="(min-width: 400px)"></div> <div data-src="large.jpg" data-media="(min-width: 800px)"></div> <div data-src="extralarge.jpg" data-media="(min-width: 1000px)"></div> <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. --> <noscript><img src="external/imgs/small.jpg" alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia"></noscript> </div>
Notes on the markup above...
altattribute is used as alternate text for the generated
div[data-picture]element can have any number of
sourceelements. The above example may contain more than the average situation would call for.
div[data-src]element must have a
data-srcattribute specifying the image path.
- It's generally a good idea to include one source element with no
mediaqualifier, so it'll apply everywhere.
data-srcelement can have an optional
mediaattribute to make it apply in different media settings. Both media types and queries can be used, like any
mediaattribute, but support for media queries depends on the browser (unsupporting browsers fail silently).
matchMediapolyfill (included in
/external) is necessary to support the
mediaattribute across browsers, even in browsers that support media queries, although it is becoming more widely supported in new browsers.
Picturefill supports a broad range of browsers and devices (there are currently no known unsupported browsers), provided that you stick with the markup conventions provided.