vue picture preload

Keywords: Javascript Vue

Objective: Picture preloading can make users browse the following pages without half of the loading of the picture leading to poor browsing.

Method 1

Pictures should be preloaded when the project opens, and pre-loaders should be added to beforeCreate in App.vue

App.vue

beforeCreate(){
    let count = 0;
    let imgs = [
    //use require The way to add the image address, add the image address directly, in the case of build The image will not be found after packaging, because the image name after packaging will have an encrypted string.
        require('xxx')
    ]
    for (let img of imgs) {
        let image = new Image();
        image.src = img;
        image.onload = () => {
            count++;
        };
    }
}

 

II. METHOD II

Create two file names, imgPreloader.js and imgPreloaderList.js. The former is used to export the asynchronous method imgPreloader for image loading, and the latter is used to store the list of images.
Then in main.js, before creating a Vue object, you have to load all the pictures before creating a Vue object and mount it on # app.

1.imgPreloaderList.js

export default [
  require('Relative picture address 1'),
  require('Relative picture address 2'),
  ...
];

2.imgPreloader.js

const imgPreloader = url => {
  return new Promise((resolve, reject) => {
    let image = new Image();
    image.src = url;
    image.onload = () => {
      resolve();
    };
    image.onerror = () => {
      reject();
    };
  });
};
export const imgsPreloader = imgs => {
  let promiseArr = [];
  imgs.forEach(element => {
    promiseArr.push(imgPreloader(element));
  });
  return Promise.all(promiseArr);
};

3.main.js

// Importing Picture Preloading Method and Picture List
import { imgsPreloader } from './config/imgPreloader.js';
import imgPreloaderList from './config/imgPreloaderList.js';

(async () => {
  await imgsPreloader(imgPreloaderList);
  //Close loading cartridge
  document.querySelector('.loading').style.display = 'none';
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount('#app');
})();

4. Loading cartridge frame

main.js mentions loading cartridges, so where should this cartridge be added? The answer is index.html

<style>
    /*
    *Style of loading cartridge frame    
    */
</style>
<body>
    <div class="loading">
    </div>
</body>

Three, summary

The effect of method 2 is more in line with the general requirements than method 1. Method 1 implements beforeMount if the picture is not fully loaded.

Posted by patelp7 on Thu, 03 Oct 2019 04:03:46 -0700