Recently I experimented upgrading the old good IMG tag using web component to 'teach' it knows how to parse srcset attribute.
Download here at Github
Just add this script after jQuery.
*Image tag with is="smart-img" *
src is optional in srcset standard, in order to avoid loading multiple images just omit it. The script will works out the best candidates as final selected source.
srcset="images/totoro.png, images/totoro2x320.png 320w, images/totoro2x360.png 360w, images/totoro2xiPad.png 768w"
The srcset regular expression was created based on the rules defined in the srcset W3C specification:
An easy to read version:
As current W3C specification stated. Width descriptors and density descriptors don't mix.
"If an image candidate string for an source or img element has the width descriptor specified, all other image candidate strings for that element must also have the width descriptor specified."
The script will use MutationObserver to monitor future added smart-img element and automatic parse srcset definition.
Browsers that doesn't support MutationObserver will fallback to use jQuery to listen 'DOMNodeInserted' event.
IE8, as usual, doesn't support neither MutationObserver or 'DOMNodeInserted' event...
I don't like to use time base polling, so I would suggest after an ajax success event, simple find img[is='smart-img'] in the new data and call each image's prototype.createdCallback()
The web component constructor will set into namespace "window.WC".
Chrome 34~37 already offer basic support of srcset. It seems only reads density definition.
To see if MutationObserver works, just run the example and click to add new image button.
- Android Browser
- Android Chrome
- Android Firefox
- iOS Safari