Img Element

One of the largest problems faced with dynamically deciding image quality is that by the time JavaScript is capable of viewing an img in the DOM, the image file has already been requested from the server. And on the flip side, if img elements are built by JavaScript, search engines probably won't view them, and browsers without JavaScript enabled will also not be able to view the images. To overcome both of these challenges, Foresight.js uses the img element, but without the src attribute set, and a noscript element with a child img element.

<img data-src="imagefile.jpg" data-width="320" data-height="240" class="fs-img">
<noscript>
    <img src="imagefile.jpg">
</noscript>

Notice how the first image is missing the src attribute, but instead has a data-src attribute. Because this img element does not have the src attribute, the browser will not attempt to download the file. Once the DOM is ready, Foresight.js does its magic to transform the data-src and set the src attribute tailored to the device's display and network connectivity. Using this structure allows us to still place img elements within the context of the webpage, while also allowing search engines and JavaScript-disabled browsers to view the images.

One concept change is that both the data-width and data-height attributes should not be seen as the image's physical dimensions in the traditional sense, but rather a way for the browser to know the image's aspect ratio as its size is scaled up and down. Foresight.js decides the image's actual dimensions, while the data-width and data-height attributes help to maintain its correct aspect ratio.

It is possible to use a numeric aspect ratio, instead of data-width and data-height, by specifying it on the data-aspect-ratio attribute. This value is used to determine the height or the width from the opposite value. If this is done, then both data-width and data-height should be left blank.

The aspect-ratio attribute also allows the height value to be determined naturally by the image returned from the server. This occurs when the value of data-aspect-ratio is "auto." Note that in this case, the the value replaced in the url for requestHeight will always be "auto" when building the src image.

Until the web community completes a new standard to hi-res context images, and it becomes widely adopted by all the major browsers, and the updated browsers are installed on the billions of devices in the world, the approach by Foresight.js is one of the few that answers each of the Challenges for High-Resolution Images.

There is hope, however, as the web community continues to work on a solution for high-resolution images. These resources offer a glimpse about what's currently being worked on (be sure to read the comments, too) Adaptive Image Element, Polyfilling picture without the overhead, and The image-set() function (for responsive images).



Have questions or feedback? Contact us.