Load images after DOMContentLoaded event, reduce image loading priority, load CSS and JS first, speed up first screen rendering

Using lazy loading

The browser parses the HTML, loads CSS and JS first, and renders the page immediately. However, images are still requesting network resources, so loading effect can be added to improve user experience

Visually, hello World appears first, followed by the image

DOMContentLoaded takes 5 s

Lazy loading is not used

Visually, hello World and the image appear at the same time

Img is encountered by browser parsing

DOMContentLoaded take 10 s

The test code

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
  <title>Document</title>
  <script>
    function lazyload() {
      let imgDomList = document.querySelectorAll("img[lazy]");
      for (let i = 0; i < imgDomList.length; i++) {
        let dom = imgDomList[i];
        if(dom.dataset.src) { dom.src = dom.dataset.src; }}}document.addEventListener("DOMContentLoaded".function () {
      setTimeout(lazyload, 0.2);
    });
  </script>
  <style>
    .lazy-img {
      width: 200px;
      height: 200px;
    }
  </style>
</head>

<body>
  <div id="root"></div>
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_223.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_224.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_225.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_226.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_227.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_228.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_229.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_230.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_231.jpg" lazy />
  <img class="lazy-img" data-src="http://cdn.leoh.io/images/base_zero/image_232.jpg" lazy />
</body>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script>
  const e = React.createElement;
  ReactDOM.render(
    e('div'.null.'Hello World'),
    document.getElementById('root'));</script>

</html>
Copy the code