18.webpack优化配置-懒加载和预加载

(一) 懒加载

  1. webpack的配置文件就是基本的配置,

    const path = require('path');
    
    const HtmlWebpackPlugin = require("html-webpack-plugin")
    
    module.exports = {
        mode: 'production',
        entry: './src/js/index.js',
        output: {
            filename: 'js/[name][contenthash:8].js',
            path: path.resolve(__dirname, 'bulid'),
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: './src/index.html'
            })
        ]
    }
    
  2. 模板文件index.html

    <button id="btn">按钮</button>
    
  3. 在入口文件index.js中

    console.log('index.js被加载');
    
    //当按钮点击后base.js文件被加载然后调用base.js文件中的mul函数
    document.getElementById('btn').onclick = function () {
        import( /* webpackChunkName: 'base'*/ './base').then(({mul}) => {
            console.log(mul(40, 3));
        }).catch((err) => {
            console.log(`base.js加载失败:${err}`);
        });
    }
    
  4. base.js文件内容

    console.log('base.js被加载');
    
    export function mul(a, b) {
      return a - b;
    }
    
  5. 打包

    webpack
    

(二) 预加载

  • 预加载prefetch:会在使用之前,提前加载js
  • 文件正常加载可以认为是并行加载(同一时间加载多个文件),预加载是等其他资源加载完毕,浏览器空闲了,再偷偷加载资源。
  • 兼容性比较差,慎用。
  1. 在懒加载的基础上,添加webpackPrefetch:true设置为预加载,修改入口文件index.js

    console.log('index.js被加载');
    
    document.getElementById('btn').onclick = function () {
        import( /* webpackChunkName: 'base',webpackPrefetch:true*/ './base').then(({
            mul
        }) => {
            console.log(mul(40, 3));
        }).catch((err) => {
            console.log(`base.js加载失败:${err}`);
        });
    }
    
  2. 这是可以在html文件中看到如下图所示的代码
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值