Home  >  Article  >  WeChat Applet  >  Implementation of mini program loader: preloading remote image resources on demand

Implementation of mini program loader: preloading remote image resources on demand

不言
不言Original
2018-09-04 17:16:052268browse

What this article brings to you is about the implementation of the mini program loader: preloading remote image resources on demand, which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I recently encountered a problem while doing H5 development. In order to prevent slow loading of large images when the page is opened, I wrote a picture resource manager and implemented it today by the way小program Version.

Special note, due to the resource package size limit of the mini program, many image resources will be stored on the CND image server. In order to load remote image resources on demand during the initialization of the mini program, the following loader has been implemented. I hope it can Solve the problem of preloading images for some new mini program developers.

Special emphasis:

This loader is a preliminary version, and other implementation methods have not been studied yet. The current implementation method needs to be implemented on the WeChat public platform- >Settings->downloadFile legal domain name, add the legal domain name of the server where the image you want to load is located.

Principle introduction:

Use the mini program’s own API to read remote image resources:

wx.getImageInfo({
 src: 'images/a.jpg',
 success: function (res) {
 console.log(res.width)
 console.log(res.height)
 }
})

This interface can create image component objects and return images Loading status.

Loader usage:

1. Create an ImageSource.js in the same directory as app.js as the path management file for image resources (can be changed according to the situation) for other file names).

2. Put ImageLoader.js or ImageLoader.min.js (attachment) in the utils folder.

3. Create an ImageLoader object in the corresponding file as needed (see below).

Usage example:

1. Loading file:

const ImageLoader = require('./utils/ImageLoader.min.js');
const ImageSource = require('./imageSource.js');

ImageLoader.min.js is the loader source file.

imageSource.js is the image resource path file.

2. Create an ImageLoader object.

new ImageLoader({
 base: ImageSource.BASE,
 source: [ImageSource],
 loading: res => {
 // 可以做进度条动画
 console.log(res);
 },
 loaded: res => {
 // 可以加载完毕动画
 console.log(res);
 }
 });

Parameters

base: String The base path of the image resource is required. Example: "https://image.example.com/static/images/"

source: Array Required example of image resources that need to be preloaded: [ImageSource.banners, ImageSource.imageList]

loading : function Callback method in image loading Non-required example:

loaded : funciton picture Non-required example of callback after recording is completed:

Loader (ImageLoader.js) source code:

let base = 0;
let Img = function(src) {
 this.src = src;
 this.status = false;
 this.fail = false;
}
 
let loop = (o, res) => {
 let tem = Object.keys(o);
 tem.map(v => {
 if (typeof o[v] === 'object') {
 loop(o[v], res);
 } else {
 if(v === 'BASE') {
 base = o[v];
 } else {
 res.push(o[v]);
 }
 }
 });
}
 
function ImageLoader(obj) {
 let arr = [];  if(obj.loading) {
 this.loadingcallback = obj.loading;
 }
 if(obj.loaded) {
 this.loadedcallback = obj.loaded;
 }
 
 if(obj.base) {
 base = obj.base
 }
 this.insert = (item) => {
 arr.push(item);
 };
 
 this.init = (o) => {
 let res = [];
 loop(o, res);
 console.log(res)
 res.map((v) => {
 this.insert(new Img(v));
 });
 this.load();
 };
 
 this.load = () => {
 this.start = (new Date).getTime();
 arr.map((v) => {
 let src = base ? base + v.src: v.src;
 wx.getImageInfo({
 src: src,
 success: res => {
 v.status = true;
 },
 fail: err => {
 v.fail = true;
 }
 })
 });
 let timer = setInterval(() => {
 let status = this.isLoaded();
 if (status) {
 clearTimeout(timer);
 }
 }, 200);
 
 setTimeout(() => {
 clearTimeout(timer);
 }, 60000);
 };
 
 this.isLoaded = () => {
 let status = true,
 count = 0,
 fail = 0;
 arr.map((v) => {
 if (!v.status) {
 status = false;
 } else {
 count += 1;
 }
 if(v.fail) {
 status = true;
 fail += 1;
 }
 });
 if(status) {
 if(this.loadedcallback) {
 this.loadedcallback({
 status: true,
 timecost: (new Date).getTime() - this.start,
 success: count,
 fail: fail,
 totalcount: arr.length
 })
 }
 } else {
 if(this.loadingcallback) {
 this.loadingcallback({
 status: false,
 percent: count / arr.length
 });
 }
 }
 return status;
 };
 if(obj.source) {
 this.init(obj.source);
 }
}
module.exports = ImageLoader

Image resource path file (imageSource.js) Source code:

module.exports = {
 "BASE": "https://img.caibeitv.com/static_project/teacherTest/static/img/",
 "single1": "ghost.4449aa4.png",
 "single2": "ghost.4449aa4.png",
 "single3": "ghost.4449aa4.png",
 "single4": "ghost.4449aa4.png",
 "pages": {
 "index": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "user": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "home": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "login": ["ghost.4449aa4.png", "ghost.4449aa4.png"]
 },
 "imageList": [
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png"
 ],
 "folders": {
 "page1": "ghost.4449aa4.png",
 "page2": "ghost.4449aa4.png",
 "inner": [
 "ghost.4449aa4.png",
 "ghost.4449aa4.png"
 ],
 "home": {
 "poster": "ghost.4449aa4.png"
 }
 }
}

Description:

BASE field is required and filled in according to your own needs.

Other image resource support:

1. Directly write the image path in the form of key: value, such as:

"single1": "ghost.4449aa4.png"

2. Similar to the pages directory, write the image path of each page The remote resources are written to the corresponding location for easy reference and management, such as:

"pages": {
 "index": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "user": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "home": ["ghost.4449aa4.png", "ghost.4449aa4.png"],
 "login": ["ghost.4449aa4.png", "ghost.4449aa4.png"]
 },

3. Directly stack the pictures in an array in array mode, such as:

"imageList": [
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png",
 "ghost.4449aa4.png"
 ]

4. Random Resource array, object nesting, such as:

"folders": {
 "page1": "ghost.4449aa4.png",
 "page2": "ghost.4449aa4.png",
 "inner": [
 "ghost.4449aa4.png",
 "ghost.4449aa4.png"
 ],
 "home": {
 "poster": "ghost.4449aa4.png"
 }
 }

This completes the configuration of the entire remote image resource loader. You can see the final status of image preloading in the loading and loaded callbacks of the new ImageLoader() object. status, the number totalcount, the number of successfully loaded pictures success, the number of failed pictures failed, and the total time cost of loading pictures (unit ms).

Instructions for the source field when creating an ImageLoader object:

new ImageLoader({
base: ImageSource.BASE,
source: [ImageSource],
loading: res => {
// 可以做进度条动画
console.log(res);
},
loaded: res => {
// 可以加载完毕动画
console.log(res);
}
});

The source field accepts an Array type parameter, based on the configuration in imageSource.js above, it is written Many different formats of data can be directly used to read various parts of data using

const ImageSource = require('./imageSource.js');

. Therefore, when configuring the source field, the entire ImageSource object can be directly put into it

source: [ImageSource]

You can also load only part of the resources according to the needs of the project, such as:

source: [ImageSource.imageList, ImageSource.single2]

In this way, the loader will only load the part written in the source during execution, rather than the entire ImageSource.

Finally, if the loading process is too time-consuming, you can choose to load resources separately in onLoad of each page. The method is similar to calling in app. The example of this article is written in onLaunch of app.js . If the loading time is too long, you can create a progress bar or loading animation to optimize the startup experience. The preloaded images will be cached in WeChat memory until the mini program process is closed, so the images can be used directly in subsequent pages.

const app = getApp();
const imgSource = require('../../imageSource.js');
Page({
 data: {
 base: imgSource.BASE,
 src: imgSource.single1
 },
 onLoad: function () {
 console.log(imgSource)
 }
})

The Image on the page will be displayed immediately, and there is no need to reinitiate the request to load the image.

Related recommendations:

JS realizes image preloading without waiting

Another small image preloading class_Picture Elephant special effects

The above is the detailed content of Implementation of mini program loader: preloading remote image resources on demand. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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