懒加载和预加载

Reads: 2090 Edit

懒加载

修改 index.js

console.log("--- load index.js ---");

import {add2, sub} from "./test"

修改 test.js

console.log("--- load test.js ---");

export function add2(x,y){
    return x + y;
}

export function sub(x,y){
    return x - y;
}

然后运行npm run build,查看构建后的index.html

1224014

懒加载可以看做延迟加载,触发了某些条件在加载,而不是一上来就加载

修改 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>    
     <h1>hello lazy loading</h1>
    <button id="btn">按钮</button>


</body>
</html>

修改 index.js

console.log("--- load index.js ---");

import {add2, sub} from "./test"

document.getElementById("btn").onclick = function(){
    console.log( add2(2,3))
}

希望点击按钮时,在加载 test.js

修改 index.js

console.log("--- load index.js ---");

//import {add2, sub} from "./test"

document.getElementById("btn").onclick = function(){
   
    import( /* webpackChunkName: 'test' */'./test')
    .then( ({add2}) => {
        console.log( add2(2,3))
    });
}

点击 按钮后 才会加载 test.js , 这就是懒加载 ,调用异步的回调函数,不会重复加载,会读取缓存里的 test.js

预加载

修改 index.js

console.log("--- load index.js ---");

//import {add2, sub} from "./test"

document.getElementById("btn").onclick = function(){
    
    // 懒加载
    // 预加载
    // 正常加载可以认为是并行加载(同一时间加载多个文件)
    // 预加载 等其他资源加载完毕后,浏览器空闲后在加载资源
    import( /* webpackChunkName: 'test' , webpackPrefetch: true */'./test')
    .then( ({add2}) => {
        console.log( add2(2,3))
    });
}

然后在 npm run build会发现 index.html已经预先加载 main.js, test.js了。

222412

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。