[Translation]-depth understanding of pictures and frames native lazy loading feature

Filled with a lot of resources on today's media websites, such as pictures and videos. Pictures accounted for about 50% of the average site traffic . However, most of these pictures no opportunity to enter the user's field of vision, because they are located on the Web page of the front page outside.

You may ask to see the title of this article "lazy loading is what?" CSS-Tricks website has a lot of discussion lazy loading of the article , which has a very detailed " implement lazy loading of JavaScript with fancy Guide document ." In short, we have to discuss is a mechanism for network resource loading delays in the mechanism, web content loaded on demand, or something more straightforward, when the web content into the user's view and then trigger load.

What are the benefits of this have to do? Compression volume to enhance the initial page loading speed; from the user will not see the contents of a waste of network requests.

If you've read other articles on lazy loading, you will understand that we must use a variety of different ways to implement lazy loading functionality. When the native HTML using loadingthe feature supports lazy loading feature, it may be a silver lining. Currently, only Chrome support loadingfeature, but is expected to fully blossom. Chrome is the recent development and testing support for native lazy loading characteristics, expected to be available in early September 2019 released 77 versions of Chrome.

Non-native method

Up to now, our group of developers still use JavaScript to achieve lazy loading functions (either zero or own handwriting from using third-party libraries). Most of the principles of lazy loading libraries are:

  • HTML response returned from the server is included in an initial, without srccharacteristic imgelement, so that the browser does not load any data. The picture on the link address imgother characteristics of the element, for example data-src.
<img data-src="https://tiny.pictures/example1.jpg" alt="...">
复制代码
  • Then, load a lazy load library, run it.
<script src="LazyLoadingLibrary.js"></script>
<script>LazyLoadingLibrary.run()</script>
复制代码
  • The lazy loading time record library user scrolls the page's behavior, tell the browser to load the user's view is about to roll into the picture. Loading is the data-srcvalue of the property originally assigned to empty srcproperties.
<img src="https://tiny.pictures/example1.jpg" data-src="https://tiny.pictures/example1.jpg" alt="...">
复制代码

For a long time, we are lazy load achieved in this way. But this is not the ideal implementation.

A significant problem with this approach is that, to show web pages, several key steps have to go through. To a total of three steps, you must have in order to perform:

  1. The initial response to loading HTML content
  2. Lazy Load to load the library
  3. Load picture

If such a lazy loading techniques applied to the picture on the front page, the page will load during flicker after, because when I started to draw, the page is no picture (flashes occur in Step 1 or Step 2, depending on the load warehousing using a script deferor async), the lazy load the library into effect, the picture was long overdue. It can also cause slow page loading illusion to the user.

In addition, the lazy load the library itself is considered occupied bandwidth and CPU power. And do not forget, if you disabled JavaScript (already in 2019, and we will not consider this situation, you say, right? ), So lazy load the library will not work.

Oh yeah, those sites (such as CSS-Tricks) rely on RSS to publish content how should we do? If the initial pages do not load images, then the RSS version of the page will not always show pictures.

All these, and so forth.

Native lazy loading to come to the rescue!

As previously mentioned, Chromium and Google Chrome development team Chrome development team from the beginning of 75, the loading loadingcharacteristics of the native support for lazy loading function. About the characteristics and values, we discuss it later, or to enable this feature in your browser to check it out now.

Enable native lazy loading feature

Chrome 75 from the start, we can switch two switches to manually enable lazy loading function. Is expected to start from the Chrome 77 (scheduled for release in September 2019), the feature will be enabled by default up.

  1. Canary open Chromium or Chrome chrome://flags.
  2. Keyword search lazy.
  3. The "Enable lazy image loading" and "Enable lazy frame loading" two are active.
  4. Click on the button in the lower right corner of the screen to restart the browser.

↑↑↑ schematic: in Google Chrome native lazy loading function switch ↑↑↑

Open the JavaScript console (press the F12button) to see if lazy loading function has been successfully activated. If successfully activated, you will see the following warning message:

[Intervention] Images loaded lazily and replaced with placeholders. Load events are deferred. (Pictures loaded and replaced with placeholder to lazy way. Load event is delayed.)

All get it? Then with deep understanding loadingof it.

loading characteristics

imgAnd iframeelements supported loadingfeatures. Remember, the loadingvalue of the property is not let the command browser strictly enforced, but to help the browser to decide whether or not to lazy loading images or frames.

The following will explain loadingthe characteristics desirable of the three values. Below each picture below, you can see a table that lists the timing of each loaded image resource. Range request (Translator's Note: the word description of Range response, suspected typo) refers to a preflight partial image request, to determine the size of the image file (see detail principle ). If the content of the column proved successful browser sent a request scope.

Note that startTime column, the list is apparent after DOM parsing, image loading was delayed for how long. You can use forced refresh (CTRL + Shift + R) to re-trigger range request.

Defaults:auto

<img src="auto-cat.jpg" loading="auto" alt="...">
<img src="auto-cat.jpg" alt="...">
<iframe src="https://css-tricks.com/" loading="auto"></iframe>
<iframe src="https://css-tricks.com/"></iframe>
复制代码

↑↑↑ schematic: automatic loading car models as ↑↑↑

Metrics / Request #1
encodedBodySize 20718 bytes
decodedBodySize 20718 bytes
transferSize 0 bytes
startTime 54 ms
requestStart 592 ms
responseStart 596 ms
responseEnd 601 ms
timeToFirstByte 4 ms
downloadDuration 5 ms

The loadingset auto(or be blank: loading=""), you can let the browser decide whether lazy loading images. Lazy loading to decide whether to consider a number of factors, such as the platform, is in the Data Saver mode (Translator's Note: Chrome was May 6, 2019 abandoned this feature), network status, image size, pictures or iframe as well as the CSS displayproperty and so on. (About the reasons to consider these factors, see here .)

Quick temper values:eager

<img src="auto-cat.jpg" loading="eager" alt="...">
<iframe src="https://css-tricks.com/" loading="eager"></iframe>
复制代码

↑↑↑ schematic: FIG ME leopard eager loading ↑↑↑

Metrics / Request #1
encodedBodySize 24019 bytes
decodedBodySize 24019 bytes
transferSize 0 bytes
startTime 54 ms
requestStart 592 ms
responseStart 600 ms
responseEnd 605 ms
timeToFirstByte 7 ms
downloadDuration 5 ms

eagerThis picture tells the browser needs immediate loading. If the load has been delayed (such as the initial value lazy, and later with JavaScript changed eager), the browser should load the picture immediately.

Lazy value:lazy

<img src="auto-cat.jpg" loading="lazy" alt="...">
<iframe src="https://css-tricks.com/" loading="lazy"></iframe>
复制代码

↑↑↑ schematic: FIG lazy loading ↑↑↑ Lanmao

Metrics / Request #1
encodedBodySize 12112 bytes
decodedBodySize 12112 bytes
transferSize 0 bytes
startTime 54 ms
requestStart 593 ms
responseStart 599 ms
responseEnd 604 ms
timeToFirstByte 6 ms
downloadDuration 5 ms

lazyThis image should tell the browser lazy loading. Lazy loading in the end how "lazy", which should be interpreted by the browser, but documentation shows that lazy loading begins with the user to scroll the page near the picture of Time, which means when the load image is coming into view.

loading Principle characteristics

And unlike lazy loading of JavaScript libraries, native lazy loading feature uses a preflight request to obtain before 2048 bytes of data image files . The data acquired in advance, the browser will try to determine the size of the image, the complete image in a position to facilitate insertion of an invisible placeholder, preventing flicker phenomenon occurs during loading the page.

After the first (if the picture size is less than 2 KB, a preflight request is enough) or the second request is completed, complete picture of a loaded, its loadevent listeners will be lifted. Note that if you do not complete the second request, the loadevent may have been the binding.

From now on, the number of requests the browser due to acquire issued picture could double. Each image corresponds to two requests: First, the scope of the request, then the request is complete. To ensure that your server supports HTTP Range: 0-2047request header and the response status code to use 206(部分内容), to prevent the entire picture is transmitted twice.

Each user will send a large number of subsequent requests, the Web server is becoming increasingly important to support HTTP / 2 protocol.

Now let's talk about the content of the delay. Chrome's rendering engine Blink uses heuristics to determine what should be delayed to load, how long delay. Scott Little in his design documents in a comprehensive list of policy conditions determine the delay. The following is a brief strategy to determine the lingering objects:

  • All platforms set loading="lazy"of pictures and frames

  • Browser for the Android system, Chrome, enable Data Saver mode; and satisfying the following conditions picture:

    • Set loading="auto"orloading=""
    • widthAnd the heightvalue of the property is not less than 10 px
    • Non-JavaScript inserted picture
  • Framework to meet the following conditions:

    • Set loading="auto"orloading=""
    • From a third party (unlike the domain name is inserted into the page or protocols)
    • Width and height greater than 4 pixels (to prevent tracing framework together micro lazy loading)
    • Is not set display: none, or visibility: hidden(preventing the tracing framework together lazy loading)
    • Value is not positioned outside the screen area with negative coordinates

With srcsetresponsive characteristics of the picture

With respect to the srcsetresponse characteristic of the picture type, native lazy loading equally effective. srcsetFeature provides a series of image files for the browser to choose. According to factor the user's screen size, device pixel ratio, network status, the browser will select the most appropriate context picture. Like tiny.pictures this image optimization CDN can provide real-time alternative picture, no back-end development .

<img src="https://demo.tiny.pictures/native-lazy-loading/lazy-cat.jpg" srcset="https://demo.tiny.pictures/native-lazy-loading/lazy-cat.jpg?width=400 400w, https://demo.tiny.pictures/native-lazy-loading/lazy-cat.jpg?width=800 800w" loading="lazy" alt="...">
复制代码

Browser support

As of this writing, there is no default browser supports native lazy loading function. But like said before, Chrome version 77 is turned lazy loading from the start by default. In addition, there is no browser vendors claim to support this feature. (Edge will be an exception, because it is about to turn Chromium kernel .)

You can use a few lines of JavaScript code to check support cases:

if ("loading" in HTMLImageElement.prototype) {
  // 支持。
} else {
  // 不支持。你可能需要引入懒加载库(下文已列出)。
}
复制代码

See CodePen in Struwe of Erk ( @erkstruwe ) code example: native browser lazy loading support probe

Fuzzy picture automatic fallback to JavaScript programs

Most of lazy loading of JavaScript-based library has a cool: fuzzy placeholder image (LQIP) . This feature basically takes advantage of this principle: Even later srccharacteristic value will be replaced another URL, browsers will begin immediately on a loaded imgelements. In this way, we can start to load a small picture is not clear when the page is loaded, then after the complete picture instead.

Now we can use this function to simulate the range of 2 KB native lazy loading request does not support lazy loading of the browser, in order to achieve the same placeholder image blur effect.

See CodePen in Struwe Erk ( @erkstruwe ) code example: for native lazy loading of JavaScript fallback plan, and the vague placeholder picture function

to sum up

This new feature really made me excited. Native lazy loading feature release in sight, global Internet communications have produced an extraordinary impact. Even if it can be changed only heuristic technology a small part, to be honest I still do not understand why people do not give enough attention.

Think about it, with the gradual promotion of Chrome in different platforms, the autovalue becomes the default option, the world's most popular browser technology is about to be loaded outside the viewport picture frame application and lazy . Burst-like traffic will be large-scale rout those sites less than robust, and, flocked picture probe request would hurt the network server.

The next is to suffer tracking technology: Suppose those trusted tracking pixels and tracking framework can not be loaded, data analysis and its surrounding areas of the industry will face a passive situation. We can only hope that they do not panic, do not give each picture will add loading="eager"this great feature, so to add loadingcharacteristics not for the service website users, it is a throwaway. They should rewrite the code, in order to be heuristic identified as tracking pixels.

Web developers, data analysis manager and operations manager should immediately check their website to ensure that front-end native support for lazy loading, back-end support range requests and HTTP / 2 protocol.

In case the primary function of lazy loading problems, or if you want to load images optimized to the limit (including automatic support for WebP, fuzzy placeholder images, etc.), image optimization CDN can help you. See more tiny.pictures !

references

If you find there is a translation error or other areas for improvement, welcome to Denver translation program to be modified and translations PR, also obtained the corresponding bonus points. The beginning of the article Permalink article is the MarkDown the links in this article on GitHub.


Nuggets Translation Project is a high-quality translation of technical articles Internet community, Source for the Nuggets English Share article on. Content covering Android , iOS , front-end , back-end , block chain , product , design , artificial intelligence field, etc., you want to see more high-quality translations, please continue to focus Nuggets translation program , the official micro-blog , we know almost columns .

Reproduced in: https: //juejin.im/post/5cfb1e36e51d45554877a597

Guess you like

Origin blog.csdn.net/weixin_33842328/article/details/91463110