vue首屏加载白屏的优化方式之一(DNS预解析网络资源)

7 篇文章 0 订阅
1 篇文章 0 订阅

1、安装依赖包

npm install node-html-parser glob url-regex

2、新增scripts目录并编写dns-prefetch.js文件

const fs = require('fs');
const path = require('path');
const { parse } = require('node-html-parser');
const { glob } = require('glob');
const urlRegex = require('url-regex');

const urlPattern = /(https?:\/\/[^/]*)/i;
const urls = new Set();
async function searchDomain() {
	const files = await glob('dist/**/*.{html,css,js}');
	for (const file of files) {
		const source = fs.readFileSync(file, 'utf-8');
		const matches = source.match(urlRegex({ strict: true }));
		if (matches) {
			matches.forEach((url) => {
				const match = url.match(urlPattern);
				if (match && match[1]) {
					urls.add(match[1]);
				}
			});
		}
	}
}

async function insertLinks() {
	const files = await glob('dist/**/*.html');
	const links = [...urls]
		.map((url) => `<link rel="dns-prefetch" href=${url} />`)
		.join('\n');

	for (const file of files) {
		const html = fs.readFileSync(file, 'utf-8');
		const root = parse(html);
		const head = root.querySelector('head');
		head.insertAdjacentHTML('afterbegin', links);
		fs.writeFileSync(file, root.toString());
	}
}

async function main() {
	await searchDomain();
	await insertLinks();
}
main();

3、在package.json的build命令添加,执行完npm run build之后在index.html查看结果

"build": "vite build && node ./scripts/dns-prefetch.js",

打包后网络资源的标签就会添加上dns-prefetch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值