1.0.2 • Published 4 months ago

@rasir/script-loader v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
4 months ago

ScriptLoader

替代 ra-script-loader

  • 动态脚本加载工具
  • 在项目中,有时候我们需要引入一些较大的 JS 库,如果直接通过打包到组件中,那么这个组件的文件尺寸就会很大。所以,我们可以在需要使用这些 JS 库的时候动态的加载相应的 min.js。就可以为组件文件节省很大的空间,同时也能提升打包速度。如果配合 CDN 使用,对前端性能提升会有很大提升。
  • 主要原理是动态加载 script 标签或者 link 标签

开始使用

npm i @rasir/script-loader -S

使用方法

import ScriptLoader from "@rasir/script-loader";

const scriptList = ["/aaa.js", "/bbb.js"];
const linkList = ["/ccc.css"];
const publicPath = "/basePath"; // 所有url的公共前缀
const rootNode = doucment.head; // script标签和link标签的父节点 默认是doucment.head
const config = {
  publicPath,
  rootNode,
  scriptList,
  linkList,
};

const scriptLoader = new ScriptLoader(config);
// 将初始化传入的js脚本和css脚本都添加到页面中 返回promise
scriptLoader.mount().then(() => {});
// 功能和mount类似,但是是链式加载js,当前一个js脚本加载完成,才会再加载下一个
// 比如这里 会等aaa.js加载完成之后在引入bbb.js的
scriptLoader.chainMount().then(() => {});
// 在mount执行前,往初始化的脚步中添加补充的脚本比如初始化脚本是 aaa.js bbb.js
// 现在调用insert之后再调用mount就会同时加载 aaa.js bbb.js ddd.js
scriptLoader.insert(["ddd.js"], ["eee.css"]).then(() => {});
// 在mount执行前,删除部分初始化的脚本
scriptLoader.delete(["aaa.js"], []).then(() => {});
// 在mount执行前,修改初始化配置
scriptLoader.modify((c) => {
  return config;
});
//  动态添加脚本
scriptLoader.add(["aaa.js"], []).then(() => {});
// 链式动态添加脚本
scriptLoader.chainAdd(["aaa.js"], []).then(() => {});
// 动态移除脚本
scriptLoader.remove(["aaa.js"], []).then(() => {});
// 将所有已加载的脚本从页面中移除
scriptLoader.unMount().then(() => {});

html 中使用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="ra-script-loader-1.0.0.min.js"></script>
  </head>
  <body></body>
  <script>
    var scriptList = ["/aaa.js", "/bbb.js"];
    var linkList = ["/ccc.css"];
    var publicPath = "/basePath";
    var rootNode = doucment.head;
    var config = {
      publicPath,
      rootNode,
      scriptList,
      linkList,
    };

    var scriptLoader = new window.ScriptLoader(config);
    scriptLoader.mount().then(() => {});
  </script>
</html>

V2.0 改进

新增 api

// 配置中添加了一个libName,可以在then中返回window中函数名
// 重新加载指定或者所有的脚本
const config = {
  scriptList: [],
  linkList: [],
  libName: "",
};
scriptLoader.remount(config).then((libName) => {});
// 重新进行链式加载指定或者所有的脚本
scriptLoader.chainRemount(config).then((libName) => {});

每次 remount 都可以有个全新的函数对象。