prefetch
, preconnect
和dns-prefetch
等资源优先级提示自动化生成工具。
配套讲解文章《1.4秒到0.4秒-2行代码让JS加载耗时减少67%》:https://juejin.cn/post/7274889579076108348
- 自动遍历构建产物,生成注入脚本,运行后注入
prefetch
资源优先级提示link
标签 - 指定域名,生成注入脚本,运行后注入
preconnect
和dns-prefetch
资源优先级提示link
标签
npm install resource-hint-generator --save-dev
module.exports = {
distPath: `./dist`,
includeFileTestFunc: (fileName) => {
return /(a.*js)|(b.*css)|(first.*js)/g.test(fileName);
},
publicPath: 'https://config.com/static/',
preconnectDomains: ['https://config.com'],
};
例如:
// package.json
"scripts": {
"generate-resource-hint": "resource-hint-generator",
"build": "cross-env NODE_ENV=production webpack && npm run generate-resource-hint",
}
配置项 | 简介 | 类型 | 默认值 |
---|---|---|---|
distPath | 打包产物路径,也是生成的resource-hint.js输出路径 | String | './dist' |
includeFileTestFunc | 指定一个函数,返回布尔值表示,遍历distPath 找到的的fileName ,是否会被作为<link rel="prefetch"> 的href 属性值 |
Function | (fileName: string) => false |
includeFileNames | 指定一个数组,数组中的字符串元素,会被作为<link rel="prefetch"> 的href 属性值 |
String[] | [] |
projectRootPath | 项目根目录路径 | String | '' |
resourceHintFileName | 生成的注入脚本名称 | String | 'resource-hint.js' |
crossOriginValue | <link> 标签crossorigin 的属性值,默认值undefined 表示无crossorigin 属性 |
String | undefined | undefined |
publicPath | 用于和includeFileTestFunc 、includeFileNames 匹配到的文件名,拼接出<link rel="prefetch"> 标签的href 属性值 |
String | '' |
preconnectDomains | 指定一个数组,数组中的每个字符串元素,都将产生2个href 属性值为当前字符串的<link rel="preconnect"> 标签和<link rel="dns-prefetch"> 标签 |
String[] | [] |
configFileName | 本地配置文件名称 | String | 'resource-hint-generator-config.js' |