webpack生产环境优化:懒加载和预加载

发布时间 2023-08-28 22:30:39作者: Eword

转载请注明 来源:http://www.eword.name/
Author:eword
Email:eword@eword.name

webpack生产环境优化:懒加载和预加载

一、直接加载

浏览器一打开,直接加载了test.js
这里使用了直接导入方式。
直接导入: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被加载了~');

二、懒加载

懒加载,当文件需要使用时才加载。
需要使用import动态导入方式。

// ./src/js/index.js
console.log('index.js被加载了~');

/*
懒加载
*/
 document.getElementById('btn').onclick = function () {
     //懒加载,当文件需要使用时才加载~
     import(/* webpackChunkName:'test' */'./test')
         .then(({ mul }) => {
             console.log(mul(4, 5));
         })
 }


核心配置

// ./src/js/index.js
     import(/* webpackChunkName:'test' */'./test')
         .then(({ mul }) => {
            //成功加载时执行。
            ……
         })
  • webpackChunkName:'test' :配置打包时的chunk名称,既文件名。

三、预加载

预加载prefetch:会在使用之前,提前加载js文件。
同样需要使用import动态导入方式。
正常加载可以认为是并行加载(同一时间加载多个文件) 预加载 prefetch:等其他资源加载完毕,浏览器空闲了,再加载资源。

//入口文件
console.log('index.js被加载了~');

/* 
预加载
*/
document.getElementById('btn').onclick = function () {
    //预加载prefetch:会在使用之前,提前加载js文件.
    //正常情况下加载可以认为是并行加载(同一时间加载多个文件)。
    //实际上预加载 prefetch会等其他资源加载完毕,浏览器空闲了,再加载设置了预加载的资源。
    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 }) => {
            //成功加载时执行。
            ……
         })
  • webpackChunkName:'test' :配置打包时的chunk名称,既文件名。
  • webpackPrefetch:true:配置预加载模式。
  • 打包时会有prefetch提示。

四、工程文件目录

# 目录结构
.
├── 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>