JSFiddle - React, Tailwind, and code Playground

by sturobson

HTML

<img src="http://odin.s0.no/web/srcset/small.png"
  srcset="http://odin.s0.no/web/srcset/big.png 1100w, 
          http://odin.s0.no/web/srcset/medium.png 500w, 
          http://odin.s0.no/web/srcset/small.png 200w" 
      alt="" 
>
<noscript><img src="http://odin.s0.no/web/srcset/small.png" alt="Noscript alt"></noscript>

<h1>What have I changed?</h1>
<ul>
<li>I've added the first img src="" which was missing from the original polyfill, this should hopefully make it a bit more #futurefriendly</li>
    <li>I've taken the display:none; out of the HTML as it was inline and pretty 'crfuty'</li>
    <li>Changed the JS display:block; to work properly with putting the CSS in the CSS</li>
</ul>

CSS

img { 
    /* added this for the designers/developers that resize their browsers ;o) */
    max-width: 100%;
    /* moved from the HTML to the CSS */
    display:none;
}
noscript img { display: inline; }


/* This is just for the comments I've included */

body {
  font-size: 14px;
  font-family: Georgia, serif;
}

p, li{
  font-size: 1em; /* 14px */
  line-height: 1.5em; /* 21px */
  margin: 0 0 1.5em 0;
}

h1 {
  font-size: 1.7143em; /* 24px */
  line-height: 1.75em; /* 42px */
  margin-top: 0.875em;
  margin-bottom: 0em;
}
h2 {
  font-size: 1.5714em; /* 22px */
  line-height: 1.9091em; /* 42px */
  margin-top: 0.9545em;
  margin-bottom: 0em;
}
h3 {
  font-size: 1.4286em; /* 20px */
  line-height: 1.05em; /* 21px */
  margin-top: 1.05em;
  margin-bottom: 0em;
}

JavaScript

// This is getting the device width 
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

// Actually implement the real `imgsrc` algorithm here
function getImgSrc(image) {
    var img_src, img_width, i,
      imgsrc_parts = image.attributes['srcset'].nodeValue.split(",");

    for (var i = 0; i < imgsrc_parts.length; i++)
    {
        var img_src = imgsrc_parts[i].match(/[^\s]+/)[0],
          img_width = imgsrc_parts[i].match(/(\d+)w/)[1];

        if (width > img_width)
            return img_src;
    }
    // Default to the last one
    return img_src;
}


var img = document.getElementsByTagName('img')[0];

// Get the real img src
img.src = getImgSrc(img);
console.log("Chose to show " + img.src);

// Set the alt text
var tmp = document.createElement("div");
tmp.innerHTML = document.getElementsByTagName('noscript')[0].textContent
img.alt = tmp.children[0].alt

// Change the style of the <img> element to display decided upon image
img.style.display = "block"