added on resize event to adjust images when resizing window
This would add a resize event to update images based in the current window size.
One possible optimization: Don't call main() on every resize but only after a timeout, so the code does not run continuously when resizing.
@jonasjonas Why does the resize use case matter to you? The downside of your approach is that resize now becomes very expensive, since a lot of JS needs to run to recalculate which image to load, etc. I don't think it's a worthwhile tradeoff.
Because I would guess that the browser would behave like this: (From the srcset-spec at http://www.w3.org/html/wg/drafts/srcset/w3c-srcset/#processing-the-image-candidates)
The user agent may at any time run the following algorithm to update an img element's image in order to react to changes in the environment. (User agents are not required to ever run this algorithm.)
I think I should optimize the resize-event not to run this code on every event call but only after a small timeout when resizing has apparently stopped.
Use case: This would be one example http://bestarchitects.de/de/2014/alle/alle/11.html – Fullscreen images in the background (technically no background-image because it's part of the content). Depending on the screen size you'll get a different image.
So if you are on the site, and then go to the fullscreen presentation mode you'll get a higher resolution image.
I think a function in the global scope that optionally accepted a list of img elements would be very helpful. It would be easy to process images onresize or when content is dynamically added.
The script should still process all images on document.readyState === "complete":
function main() {
// ...
processSrcset(); // assume document.querySelectorAll("img")
}
But a developer could call the function with a list of images at any time:
window.onresize = debounce( function (e) {
processSrcset();
}, 250, false );
// or
$.get( "ajax/content.html", function ( data ) {
$( ".result" ).html( data );
processSrcset( $( ".result img" ) );
});
The global function should be there, because otherwise we won't be able to use it with ajax requested images.
For the resize case: A global function would be, but I still think the resizing part should be part of the polyfill itself...
Global function makes a lot of sense.
used with a library like underscore in a modern JS app:
var lazyprocessSrcset = _.debounce(processSrcset, 300);
$(window).resize(lazyprocessSrcset);
At present it is impossible to use this polyfill with dynamic content due to the fact it only fires on page load.