QR Code contains TinyURL of this article.Load JavaScript Conditionally, with Feature Detection

I’ve made one or two changes to the Perpetual βeta recently so as to improve the experience for MSIE & Edge users. One of my revisions was to reinstate the Picturefill responsive images polyfill, which I had previously removed in the mistaken belief that all browsers now support srcset and sizes (we’re not there yet).

For performance reasons, I didn’t want to load Picturefill where I did not need it. I needed to load it conditionally.

Back in the day, for MSIE at least, we would accomplish this task with that browser’s conditional comments. Something like:

<!--[if IE]>
// do this thing only if the client web-browser is MSIE

Unfortunately, MSIE 10+ and Edge do not support conditional comments. This is a good thing, as the best practice these days eschews such hacks in favour of the more semantically correct principle of feature detection — in which we attempt to identify the availability, or otherwise, of a feature rather than target a specific web-browser.

So, with best practice in mind, I have used the following JavaScript to load picturefill.js in those instances where srcset and sizes are not available:

function polyfillImages() {
  // create an image node so we can test its properties
  var img = document.createElement('img');
  // feature detect
  var supportSrcset = ('srcset' in img) && ('sizes' in img);
  if (!supportSrcset) {
    // feature not available:
    // create a script tag
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/path/to/picturefill.min.js';
    script.setAttribute('async', '')
    // add it to the document <head>...
    var head = document.getElementsByTagName('head')[0];

// call the method

Boom… my responsive images now work perfectly in those web-browsers that lack support for srcset and sizes and the more standards-compliant clients do not incur the overhead of downloading an unnecessary asset.