Knowledge about

Why

Lazy loading is a kind of lazy loading technology. A large number of images in a long web page affect the loading speed and user experience. Lazy loading is a way to optimize web page performance. A lot of use in emporium scenes.

For example, the homepage of JINGdong only needs to complete the task of displaying on the first screen as soon as possible, and other pictures can be downloaded along with the scrolling of the page.

What

The principle of lazy loading is to change the entire download from a one-time download to a viewable area download. Which means you can download it wherever you see it.

  • Image SRC does not set the real path
  • The actual path of the image is set in other properties such as data-original
  • Use JS to determine whether the picture has entered the viewable area.
  • Change the image SRC to the real path if the image is in the viewable area

HOW

Step01: The SRC of the picture does not set the real path, the real path set data-original

    <img
      src=""
      class="image-item"
      lazyload="true"
      data-original="https://gitee.com/josephxia/picgo/raw/master/juejin/image-20220124221805647.png?a=1"
    />
Copy the code

Step02: Judge whether the picture enters the visible area by JS. If the picture enters the visible area, change the picture SRC to the real path

var viewHeight = document.body.clientHeight; Function lazyload() {console.log('load') var list = document.querySelectorAll("img[data-original][lazyload]"); list.forEach((item) => { if (item.dataset.original === "") return; var rect = item.getBoundingClientRect(); If (rect.bottom >= 0 && rect.top < viewHeight) {var img = new Image(); img.src = item.dataset.original; img.onload = function () { item.src = img.src; }; item.removeAttribute("data-original"); Item.removeattribute (" lazyLoad "); }}); } lazyload(); / / started haven't scroll the screen as to trigger a function first, initialize the page page picture document. The addEventListener (" scroll ", the lazyload);Copy the code

The interview guide

Lazy loading technology is widely used in long pages on the home page of e-commerce. We must understand the principle and try this code ourselves.

\