什么是按需加载:

当页面中一个文件过大并且还不一定用到的时候,我们希望在使用到的时候才开始加载这个文件俗称按需加载。这样可以减少页面的响应时间,提高访问速度。

按需加载的实现方式:

使用webpack打包的出来的文件要实现以上的要求有两种方式,一个是webpack特有的require.ensure方法,还有一个是import()方法。

方法一:

require.ensure()方法:require.ensure(dep: array, cb: function, name?: string)

第一个参数是该模块的依赖,第二个参数是模块加载完成后执行的回调,第三个参数是对应webpack.config.js中output.chunkFilename: ‘[name].js’ 中的name。

样例:

index.html文件:
<button id='btn'>点击我</button>


index.js文件:
document.querySelector('#btn').onclick = function () {
  require.ensure([], function () {
    let a = require('./asynca.js')
    console.log('asynca模块加载完毕:'a)
  }, 'asynca')
}


asynca.js文件:
console.log('我是async模块')
export const a = '模块async'


webpack.config.js文件:
let path = require('path')
let HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve('./dist'),
    filename: '[name].[chunkHash].js',
    chunkFilename: '[name].[chunkHash].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html'
    })
  ]
}

asynca文件被动态加载进来,并且require.ensure的回调函数被执行了。

方法二:

import():该方法返回一个promise,文件加载完成之后会将模块导出给promise的回调。

document.querySelector('#btn').onclick = function () {
  console.log('我是通过import来实现按需加载的')
  let a = import('./asynca.js')
  a.then(function (res) {
    console.log('加载完成的async模块', res)
  })
}

  

参考:https://blog.csdn.net/letterTiger/article/details/89299606 

 

posted on 2020-10-28 18:03  liumcb  阅读(1189)  评论(0编辑  收藏  举报