bbc / Imager.js

Responsive images while we wait for srcset to finish cooking
Apache License 2.0
3.84k stars 224 forks source link

Aspect ratio of images while loading page #139

Open mindplay-dk opened 7 years ago

mindplay-dk commented 7 years ago

On a news site with 100+ images on the front-page, one of our devs was using a lowsrc to make sure the image elements on the page would maintain size initially - this of course resulted in server problems due to the sheer volume of requests.

Our solution was to put a wrapper-element around every image placeholder, e.g. using CSS like:

.image-wrapper {
    width: 100%;
    position: relative;
    overflow: hidden;
}

.image-wrapper > img {
    position: absolute;
    left: 0;
    top: 0;
}

In other words, we get the image width/height on the server-side, calculate the aspect-ratio in percent, and use padding-bottom to maintain aspect ratio of the wrapper element:

<div class="image-wrapper" style="padding-bottom:62.25%">
    ... response image here ...
</div>

This works - the page loads without anything jumping around.

This approach works because this site is responsive, loading the same image at different resolutions - but would not work if the site was adaptive, e.g. if it was loading versions of the image with different aspect ratios to match design variations on smaller devices.

This makes me wonder - currently, Imager only needs to care about image widths, since the height is calculated by the browser when the images load. Could we have support for optionally specifying both the width and height of each image version?

This would enable the script to create wrappers around generated image-elements, using an approach similar to what I described above - which would enable responsive (and adaptive) images to initially (or at least very early) reserve the amount of space they need, so that things don't jump around while the page is loading.

Thoughts?