webpack生產(chǎn)環(huán)境優(yōu)化:懶加載和預(yù)加載
轉(zhuǎn)載請注明 來源:http://www.eword.name/
Author:eword
Email:eword@eword.name
webpack生產(chǎn)環(huán)境優(yōu)化:懶加載和預(yù)加載
一、直接加載
瀏覽器一打開,直接加載了
test.js
這里使用了直接導(dǎo)入方式。
直接導(dǎo)入:import { mul } from './test';
// ./src/js/index.js
//入口文件
console.log('index.js被加載了~');
/* 直接加載了 */
import { mul } from './test';
console.log(mul);
document.getElementById('btn').onclick = function () {
console.log(mul(4, 5));
}
核心配置
// ./src/js/index.js
console.log('index.js被加載了~');
二、懶加載
懶加載,當(dāng)文件需要使用時(shí)才加載。
需要使用import動態(tài)導(dǎo)入方式。
// ./src/js/index.js
console.log('index.js被加載了~');
/*
懶加載
*/
document.getElementById('btn').onclick = function () {
//懶加載,當(dāng)文件需要使用時(shí)才加載~
import(/* webpackChunkName:'test' */'./test')
.then(({ mul }) => {
console.log(mul(4, 5));
})
}
核心配置
// ./src/js/index.js
import(/* webpackChunkName:'test' */'./test')
.then(({ mul }) => {
//成功加載時(shí)執(zhí)行。
……
})
webpackChunkName:'test':配置打包時(shí)的chunk名稱,既文件名。
三、預(yù)加載
預(yù)加載prefetch:會在使用之前,提前加載js文件。
同樣需要使用import動態(tài)導(dǎo)入方式。
正常加載可以認(rèn)為是并行加載(同一時(shí)間加載多個(gè)文件) 預(yù)加載 prefetch:等其他資源加載完畢,瀏覽器空閑了,再加載資源。
//入口文件
console.log('index.js被加載了~');
/*
預(yù)加載
*/
document.getElementById('btn').onclick = function () {
//預(yù)加載prefetch:會在使用之前,提前加載js文件.
//正常情況下加載可以認(rèn)為是并行加載(同一時(shí)間加載多個(gè)文件)。
//實(shí)際上預(yù)加載 prefetch會等其他資源加載完畢,瀏覽器空閑了,再加載設(shè)置了預(yù)加載的資源。
import(/* webpackChunkName:'test', webpackPrefetch:true */'./test')
.then(({ mul }) => {
console.log(mul(4, 5));
})
}
核心配置
// ./src/js/index.js
import(/* webpackChunkName:'test', webpackPrefetch:true */'./test')
.then(({ mul }) => {
//成功加載時(shí)執(zhí)行。
……
})
webpackChunkName:'test':配置打包時(shí)的chunk名稱,既文件名。webpackPrefetch:true:配置預(yù)加載模式。- 打包時(shí)會有
prefetch提示。

四、工程文件目錄
# 目錄結(jié)構(gòu)
.
├── src
│ ├── index.html
│ └── js
│ ├── index.js //入口文件
│ └── test.js //被加載的文件
└── webpack.config.js
// ./src/js/test.js
console.log('test.js被加載了~');
export function mul(x, y) {
return x * y;
}
export function count(x, y) {
return x - y;
}
<!-- ./src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack</title>
</head>
<body>
<H1>hello lazy loading</H1>
<button id="btn">加載</button>
</body>
</html>

浙公網(wǎng)安備 33010602011771號