懒加载/预加载

懒加载:当文件需要使用时才加载

预加载:会在使用之前,提前加载js文件(等其他资源加载完毕,浏览器空闲了,在偷偷加载资源,适用于pc端)兼容性问题严重,caniuse查看是否使用该技术

​ 扩展:正常加载可以认为是并行加载(同一时间加载多个文件)

//test.js
console.log('test.js文件被加载了');

export function mul(a, b) {
  return a * b
}
// console.log(mul);

export function sum(...args) {
  return args.reduce((p, c) => p + c, 0)
}
//index.js 入口文件
document.getElementById('btn').onclick = function () {
  // 懒加载,页面要点击按钮之后,请求test.js文件
  // 预加载prefetch:会在使用之前,提前加载js文件 webpackPrefetch:true
  import(/*webpackChunkName:'test',webpackPrefetch:true */'./test').then(({ mul, sum }) => {
    console.log(mul(1, 2));
    console.log(sum(1, 2, 3, 4));
  }).catch(() => {
    console.log('文件加载错误');
  })
}

console.log('index.js文件被加载了');
posted @ 2021-12-07 10:37  STRIVE-PHY  阅读(117)  评论(0编辑  收藏  举报