[Proposal] Manually loading image sources based on preset conditions


#1

There have been a number of topics pointed out that do a good job of identifying that there is currently no way to easily lazy load images (i.e. when user is scrolling down a page for instance).

Many valid points have been brought up but I think the issue of lazy-loading images has become way too large to solve in one single solution. As I’ve stated in one of my comments on that topic, the two biggest issues, that seem to come up often, that the solution could address are 1) being able to manually load the image source at any given time or 2) letting the browser automatically trigger loading at some pre-determined time the browser thinks is “most optimal”.

I do not think #2 can be solved now since it involves too many assumptions for my liking, but I do believe that solving #1 is a reasonable first step to at least gain a little more traction on the issue.

I am proposing that we implement a load() method to the HTMLImageElement api that will load the resource based on an array of possible images to load per device, set via the srcset attribute or similar). I’ve already began the proposal on a Github repo here.

Calling load() on an element with the following markup will manually load the appropriate image just like the existing srcset spec explains:

<img srcset="medium.jpg 1000w, large.jpg 2000w" autoload="false" />

It may be interesting to even determine latency to load lower resolution images on slower connections vs higher-res on faster ones (using the Navigation Timing API or similar). Array like string on srcset could use milliseconds that represent latency measures:

<img srcset="small.jpg 10000, large.jpg 500" autoload="false" />

This load() call could return a promise that is resolved or rejected when completed. And to make it even more flexible from a JS standpoint, it can be improved to accept an optional argument that could alternatively represent the HTML attributes in the examples above or to just add more custom functionality.

Interested in hearing your thoughts.