Skip to content

Instantly share code, notes, and snippets.

@greenboyroy
Last active February 9, 2016 16:53
Show Gist options
  • Save greenboyroy/e9cfda3542340053d5df to your computer and use it in GitHub Desktop.
Save greenboyroy/e9cfda3542340053d5df to your computer and use it in GitHub Desktop.
Get Picturefill if required

Picturefill if Required

Picture, srcset and sizes is now gaining some traction in browsers so why download picturefill by default? This gist (hopefully) only loads picturefill if it is required using a test from picturefill itself.

Test it out here

Tests

  • Safari 8 (Poor support, loads picturefill)
  • Safari 9 (Limited support, loads picturefill)
  • Chrome 45 (Good support, picturefill not required, doesn't load)
  • Firefox 40 (Good support, picturefill not required, doesn't load)
  • Opera 31 (Good support, picturefill not required, doesn't load)
  • IE 8 (Haha, what is this support word? loads all the things)
  • IE 9 (Poor support, loads picturefill)
<!doctype html>
<html class="no-js" lang="en-GB">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Picturefill when required</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<!--<![endif]-->
<script>
// Picture element HTML5 shiv for older, non IE browsers
document.createElement("picture");
var image = new window.Image();
// Check for support, if lacking load picturefill and run it once loaded.
if (("srcset" in image === false) || ("sizes" in image === false) || ("currentSrc" in image === false)) {
var pf = document.createElement("script");
pf.src = "https://cdnjs.cloudflare.com/ajax/libs/picturefill/3.0.1/picturefill.min.js";
pf.type = "text/javascript";
pf.async = "true";
pf.onload = pf.onreadystatechange = function() {
var rs = this.readyState;
if (rs && rs != 'complete' && rs != 'loaded') return;
try { picturefill(); } catch (e) {}
};
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(pf, s);
}
// Look familiar? It's just like the Typekit loader.
</script>
</head>
<body>
<img src="https://placehold.it/480x320"
srcset="
https://placehold.it/1200x800 1200w,
https://placehold.it/992x662 992w,
https://placehold.it/768x512 768w,
https://placehold.it/480x320 480w"
sizes="(min-width: 75em) 75em, 100vw"
alt="Wide Image"
/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment