• Native image lazy-loading for the web!
  • Original post by addyosmani
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: nanjingboy
  • Proofreader: Xionglong58, Portandbridge

In this article, we’ll examine the new loading property, which brings lazy-loading capabilities to and

<img src="celebration.jpg" loading="lazy" alt="..." />
<iframe src="video-player.html" loading="lazy"></iframe>
Copy the code

We hope to provide support for Loading in ~Chrome 75, and we’re digging into upcoming features. Before we do that, let’s take a closer look at how it works.

Introduction to the

Web pages often contain a large number of images, which can affect network traffic, page size, and page loading speed. Many of these images are off-screen and often require the user to scroll to see them.

In the past, to reduce the impact of off-screen images on page load times, developers had to use JavaScript libraries such as LazySizes to delay the loading of these images until the user had scrolled the page near them.

Page loaded 211 images. The version without lazy loading loaded 10 MB of data. The lazy-loaded version (using LazySizes) only preloads 250 KB of data – other images will load as the user scrolls. View the WPT.

What if the browser could help you avoid loading off-screen images? This will help speed up content loading in Windows and reduce overall network data and memory usage on low-end devices. So I’m happy to report that it will soon be possible to use the new property Loading of image and iframe.

loadingattribute

The loading property allows the browser to delay loading off-screen images and iframes until the user scrolls the page near them. Loading supports three values:

  • Lazy: indicates lazy loading.
  • Eager: loads immediately.
  • Auto: The browser determines whether to load lazily.

If this attribute is not specified, the default value is auto.

The HTML standard is investigating the loading properties of and

example

Loading properties apply to (including srcset and inside ) and

<! -- Lazily loading an off-screen image until the user scrolls near it -->
<img src="unicorn.jpg" loading="lazy" alt=".."/>

<! Load images immediately (not lazily) -->
<img src="unicorn.jpg" loading="eager" alt=".."/>

<! The browser decides whether to lazily load images.
<img src="unicorn.jpg" loading="auto" alt=".."/>

<! Lazy loading of pictures in <picture> <img> is used to drive image loading, so <picture> and srcset will render the appropriate image on <img> -->
<picture>
  <source media="(min-width: 40em)" srcset="big.jpg 1x, big-hd.jpg 2x">
  <source srcset="small.jpg 1x, small-hd.jpg 2x">
  <img src="fallback.jpg" loading="lazy">
</picture>

<! -- Lazy load srcset -->
<img src="small.jpg"
     srcset="large.jpg 1024w, medium.jpg 640w, small.jpg 320w"
     sizes="(min - width: 36 em) 33.3 vw, 100 vw"
     alt="A rad wolf" loading="lazy">

<! Delay loading the off-screen iframe until the user scrolls near it -->
<iframe src="video-player.html" loading="lazy"></iframe>
Copy the code

The exact detection of “when the user scrolls nearby” is done by the browser. In general, we want the browser to start extracting delayed images and iframe content almost before entering the view window. This adds changes to images or iframes that are loaded when the user scrolls to them.

Note: I once suggested that the loading attribute value should be used as the attribute name, because its name is similar to the decoding attribute. In the previous proposal, attributes like LazyLoad were not accepted because we needed to support multiple values (lazy, eager, and Auto).

Feature detection

We already know the importance of acquiring and applying JavaScript libraries for lazy loading (cross-browser support). You can check whether loading is supported in the following ways:

<script>
if ('loading' in HTMLImageElement.prototype) {
    // Browsers support 'loading'..
} else {
   // Get and apply the Polyfill /JavaScript library
   // instead of lazy-loading.
}
</script>
Copy the code

Note: You can also use loading as a progressive enhancement. Browsers that support this property gain the new lazy loading capability with Loading =lazy, while browsers that do not support this property will still load images.

Lazy loading of images across browsers

If it is important to support lazy loading of images across browsers, it is not enough to simply feature detect in tags with and use lazy loading libraries.

The tag needs to use attributes like (instead of SRC, srcset, or) to avoid triggering immediate loading in browsers that do not support the new attribute. If the browser supports loading, you can use JavaScript to change these properties to the correct ones, otherwise load the class libraries.

Here’s an example of what it might look like.

  • Window/one screen display images are normal<img>The label.data-srcIt breaks the preloaded scanner, so we want to avoid it in everything in the viewport.
  • We use it on picturesdata-srcTo avoid triggering immediate loading in unsupported browsers if the browser supports itloadingAnd we willdata-srcReplace withsrc.
  • ifloadingNot supported, we load a backup script (LazySizes) and start it. In this case, we useclass=lazyloadIndicate to LazySizes which images to load lazily.
<! Let's load this image in Windows as normal -->
<img src="hero.jpg" alt=".."/>

<! Let's load the rest of the images lazily -->
<img data-src="unicorn.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="cats.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="dogs.jpg" loading="lazy" alt=".." class="lazyload"/>

<script>
(async() = > {if ('loading' in HTMLImageElement.prototype) {
        const images = document.querySelectorAll("img.lazyload");
        images.forEach(img= > {
            img.src = img.dataset.src;
        });
    } else {
        // Dynamically introduce LazySizes library
        const lazySizesLib = await import('/lazysizes.min.js');
        // Initialize LazySizes (read data-src & class= lazyLoad)
        lazySizes.init(); // lazySizes works in a global environment.
    }
})();
</script>
Copy the code

The sample

Look at this! A loading=lazy example shows a full 100 pictures of kittens.

Be /bhnfL6ODM68

Chrome Implementation Details

We strongly recommend waitingloadingProperty is in stable version before you use it in your production environment. Early testers may find the following annotations useful.

Immediately try to

Go to Chrome ://flags and Enable both “Enable lazy frame Loading “and “Enable lazy image Loading”, then restart Chrome.

configuration

Chrome’s implementation of lazy loading is not only based on the proximity of the current scroll position, but also on the speed of the network connection. For different network connection speeds, the window distance threshold for lazy loading frame and picture is hard-coded and can be overridden by the command line. Here is an example that overrides the image lazy loading Settings:

canary --user-data-dir="$(mktemp -d)"--enable-features=LazyImageLoading --blink-settings=lazyImageLoadingDistanceThresholdPxUnknown=5000,lazyImageLoadingDistanceThresholdPxOffline=8000,lazyIma geLoadingDistanceThresholdPxSlow2G=8000,lazyImageLoadingDistanceThresholdPx2G=6000,lazyImageLoadingDistanceThresholdPx3G =4000,lazyImageLoadingDistanceThresholdPx4G=3000'https://mathiasbynens.be/demo/img-loading-lazy'
Copy the code

The above commands correspond to the (current) default configuration. Change all values to 400 to start lazy loading only at the scroll position within 400 pixels of the image. Here we can also see another way to set the distance threshold to 1 pixel (used in previous videos in this article) :

canary --user-data-dir="$(mktemp -d)"--enable-features=LazyImageLoading --blink-settings=lazyImageLoadingDistanceThresholdPxUnknown=1,lazyImageLoadingDistanceThresholdPxOffline=1,lazyImageLoad ingDistanceThresholdPxSlow2G=1,lazyImageLoadingDistanceThresholdPx2G=1,lazyImageLoadingDistanceThresholdPx3G=1,lazyImage LoadingDistanceThresholdPx4G=1'https://mathiasbynens.be/demo/img-loading-lazy'
Copy the code

Our default configuration is likely to change as the implementation stabilizes over the next few weeks.

DevTools

One implementation detail of Loading in Chrome is that it gets the first 2 KB of image data when the page loads. If the server supports range requests, the first 2 KB may contain the image size. This allows us to generate/display placeholders of the same size. For resources such as ICONS, the first 2 KB will probably contain the entire image.

Chrome grabs the rest of the image’s data just as the user is about to see it. The caveat in Chrome DevTools is that this can result in (1) two “occurrences” of fetch in the DevTools Web panel and (2) two resource timing requests per image.

Server determinationloadingsupport

In a good world, you wouldn’t need to rely on JavaScript feature detection on the client side to determine whether compatible libraries need to be loaded or not — you’d need to deal with this before serving HTML containing JavaScript lazy-loaded libraries. The client prompts you to enable this type of check.

Hints for passing loading parameters have been considered, but are currently in the early stages of discussion.

conclusion

Try and let us know what you think. I’m particularly interested in how you explore the cross-browser experience and if there are any edge cases that we’ve missed.

The resources

  • Intent to ship this feature in Blink
  • Specification PR
  • Explainer
  • Demo

Thanks to Simon Pieters, Yoav Weiss and Mathias Bynens for their feedback. Many thanks to Ben Greenstein, Scott Little, Raj T and Houssein Djirdeh for their work on LazyLoad.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.