DNS
# DNS 解析优化
优化思路
- dns 初次解析会耗时,解析完会做短暂的缓存
- 当页面引入外部域名资源时,会增加页面加载时间,可以考虑提前异步解析 dns
解决方法
<!-- 在 head 标签里加入 link 提前引入外部域名 --> <link rel="dns-prefeetch" href="https://a.com" /> <link rel="dns-prefeetch" href="https://a.com" /> ...
具体项目实现,使用脚本在打包时自动添加到入口文件
# 安装依赖 npm i node-html-parser glob url-regex
// 新建 dns-prefetch.js 文件 const fs = require('fs') const { parse } = require('node-html-parser') const { glob } = require('glob') const urlRegex = require('url-regex') // 获取外链正则 const urlPatt = /(https?:\/\/[^/]*)/i // 定义外链列表,使用 set 可以去重 const urls = new Set() // 遍历 dist 目录中的所有 html,js,css 文件 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(urlPatt) if (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()
// 修改 package.js 文件 build,加入打包后插入操作 "scripts": { ... "build": "vite build && node ./scripts/dns-prefetch.js", ... },