Home > Web Front-end > JS Tutorial > js to implement image preloading

js to implement image preloading

王林
Release: 2020-05-17 09:21:23
forward
3710 people have browsed it

js to implement image preloading

What is preloading:

When the page opens, pictures are loaded in advance and cached locally in the user's local area. They are rendered directly when needed; when browsing a lot of pictures Web pages (Baidu Gallery, Taobao JD.com, etc.) can have a better user experience;

Preloading of a picture

var img=new Image();
    img.addEventListener("load",loadHandler);
    img.src="./img/1.jpg";
    document.body.appendChild(img);
    console.log(img.width);

    function loadHandler(e){
      console.log(img.width);//当前图片的原始宽度
    }
Copy after login

In the above code, the picture has not been loaded yet and the width of the printed picture is When, the image width is 0; only after the image is loaded and written into the DOM tree for rendering, can the callback function of the load event be triggered to print out the width of the image;

When loading multiple images, you need to Caching locally in advance, here are three examples of preloading multiple images:

First: load preloading

Load 100 images, and the image name is 1.jpg ~100.jpg (the same below);

var num=1;
    var list=[];
    loadImage();
    function loadImage(){
      var img=new Image();
      img.addEventListener("load",loadHandler);
      img.src="./img/"+num+".jpg";
    }
    function loadHandler(e){
      list.push(this.cloneNode());//复制当前图片元素
      num++;
      if(num>100){console.log(list);return;}
      this.src="./img/"+num+".jpg"; //修改地址继续后触发load事件
    }
Copy after login

The above code indicates:

1. Create a picture;

2. Add event detection to this picture Listen to load;

3. After the loading is completed, copy the loaded image into a new one and put it in the array;

4. Modify num; if num If the value is greater than 100, the execution will stop and the array will be printed;

5. Give a new address to the address of this image. Because changing the address of the image will re-trigger load, so it will continue to enter the loadHandler function, continuously Load until loading is complete.

Second type: Generator function implements preloading

function loadImage(src){
    return new Promise(function(resolve,reject){
      let img=new Image();
      img.onload=function(){ 
        resolve(img);//加载时执行resolve函数
      }
      img.onerror=function(){ 
        reject(src+'这个地址错误');//抛出异常时执行reject函数
      }
      img.src=src;
    })
  }
  function* fn(){
    for(let i=1;i<100;i++){
      yield loadImage("./img/"+i+".jpg");
    }
  }
  let s=fn();
  let value=s.next().value; 
  resume();
  function resume(){
    value.then(img=>{
      console.log(img);//打印加载的图片标签
      value=s.next().value;
      if(value)resume();
    });
  }
Copy after login

The above code indicates:

1. Execute the generator function and execute the loadImage function once;

2. Create the image in Promise;

3. Determine whether the image can be loaded, and execute the Promise callback function resolve if the loading is successful;

4. Execute the resume function once, and The function executes the Promise function in the resolved state

5, repeatedly executes s.next().value until all images are loaded;

The third method: async/await preloads images

function loadImage(src){
    let p=new Promise(function(resolve,reject){
      let img=new Image();
      img.onload=function(){//加载时执行resolve函数
        resolve(img);
      }
      img.onerror=function(){
        reject(src);
      }
      img.src=src;
    })
    return p;
  }
  async function fn(){
    let arr=[];
    for(let i=3;i<80;i++){
      await loadImage(`./img/${i}-.jpg`).then(img=>{
        arr.push(img);
      });
    }
    return arr;
  }
  fn().then(list=>{
    console.log(list);//打印图片数组
  })
Copy after login

This method is an ES6 method that uses async and await to convert asynchronous into blocking synchronization;

Explanation:

1. fn This function uses async to represent this The function is an asynchronous function

2. You can use await in this function. The function of await is to turn asynchronous into synchronous waiting, and asynchronous into blocking waiting

3. When all asynchronous operations are completed, continue running backwards

4. The await in the async function can only be followed by the Promise object

5. The async function What is returned after execution is a Promise object

Recommended tutorial:js introductory tutorial

The above is the detailed content of js to implement image preloading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template