Responsive images

by mathieumaes

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/picturefill/2.3.1/picturefill.min.js"></script>
<!--
  Use case: feeding smaller versions of an image to smaller screens. According to specs, one must add sizes and srcset attributes to a single <img> tag.

 <picture> and <source> elements are intended for other use cases, but are nevertheless added for 2 reasons:
 - Chrome always uses high-res image on retina/hiDPI screens.
 - Mobile devices with high resolutions (ie. Samsung S6) still use large images which is not ideal on mobile connection

Polyfill Javascript is required for IE and older browsers not supporting srcset, including previous iOS versions.
-->
<picture>
    <source media="(max-width: 768px)"
            srcset="https://placeholdit.imgix.net/~text?txtsize=33&txt=small&w=768&h=134">
    <img
         alt=""
         sizes="100vw"
         src="https://placeholdit.imgix.net/~text?txtsize=33&txt=small&w=768&h=134"
         srcset="
         https://placeholdit.imgix.net/~text?txtsize=33&txt=small&w=768&h=134 768w,
         https://placeholdit.imgix.net/~text?txtsize=100&txt=large&w=2000&h=350 2000w"
         class="header-picture slide-picture">
</picture>

CSS

img {
    width: 100%;
}

JavaScript

// Picturefill is loaded as an external resource!
document.getElementByTagName('head').innerHTML += '<meta name="viewport" content="width=device-width, initial-scale=1" />';