1.说明

有些文件并非页面打开就需要加载的,但是又是被页面js所引用的。
比如主js中有一个点击事件引用了另一个事件js文件
浏览器的默认行为时,加载了主js,再去加载事件js。并将两个文件都执行。
然而 主js页面渲染时,其实不需要事件js文件的。
只有按钮点击之后才需要去加载这个事件js

解决方法:

  • 懒加载
    • 点击按钮后采取加载指定文件
    • 兼容性良好,但是如果懒加载的文件如果太大就会感觉突然点击无时间一样。
  • 预加载
    • 页面渲染后,将文件都加载上,但是只是在事件触发时才执行文件。
    • 兼容性不好。

2.案例

2.1.index.html

src\index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <button id="btn">btn</button>
  9. </body>
  10. </html>

2.2.test.js

src\js\test.js

console.log('test.js 被加载')

export function mul(x, y) {
    return x - y
}

2.3.index.js

其实懒加载和按需加载是一样的。只是如果放在function中就不会第一时间被执行,所以就成为了懒加载。
当加上webpackPrefetch: true之后就是预加载了。
所以如果不需要预加载,就把webpackPrefetch: true删除。
src\js\index.js

console.log('index.js 被加载')

document.getElementById("btn").onclick = function () {
    import(/* webpackChunkName: "testRename", webpackPrefetch: true */"./test")
        .then(({ mul }) => {
            console.log(mul(5, 9))
        })
        .catch(() => {
            console.log('文件加载失败')
        })
}

2.4.webpack.config.js

webpack.config.js

const { resolve } = require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode: 'production',
    devtool: 'source-map',
    entry: './src/js/index.js',
    output: {
        filename: 'js/[name].[contenthash:10].js',
        path: resolve(__dirname, 'build')
    },
    plugins: [
        new HtmlWebpackPlugin({
            // 模板位置
            template: './src/index.html',
            minify: {
                collapseWhitespace: true,
                removeComments: true,
            }
        })
    ],
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
}