vue打包优化之dns解析优化(dns预解析)

一、优化原理

1.简单描述dns解析是什么

用户输入域名==>查询本地有没有记录==>本地没有记录则发起请求询问ip地址

2.为什么需要优化

dns解析是一个耗时操作,在浏览器解析Html时如果遇见了需要解析的域名会导致阻塞。

3.优化思路

将html中的链接提前到<head>中使用<link rel="dns-prefetch">预先解析可能用到的域名

二、代码实现

需要安装的包:

npm install node-html-parser

npm install glob

npm install url-regex

dns-prefecth.js:

javascript 复制代码
import * as fs from "fs";
//npm install node-html-parser
//用于解析html文件
import { parse } from "node-html-parser";
//npm install glob
//用于获取文件列表
import { glob } from "glob";
//npm install url-regex
//用于匹配url
import urlRegex from "url-regex";

//获取外部链接正则表达式
const urlPattern = /(https?:\/\/[^\s]+)/i;

//用于存储所有外部链接
const urls = new Set();

//异步搜索所有html文件中的外部链接
async function searchDomain() {
  const files = await glob("dist/**/*.{html,js,css}");
  for (const file of files) {
    //读取文件内容
    const source = fs.readFileSync(file, "utf-8");
    //匹配外部链接
    const matches = source.match(urlRegex({ strict: true }));
    if (matches) {
      //将匹配到的外部链接添加到urls集合中
      matches.forEach((url) => {
        const match = url.match(urlPattern);
        if (match && match[1]) {
          urls.add(match[1]);
        }
      });
    }
  }
}

//异步在head中插入链接
async function insertLinks() {
  //获取所有html文件
  const files = await glob("dist/**/*.html");
  //生成链接
  const links = [...urls]
    .map((url) => `<link rel="dns-prefetch" href="${url}">`)
    .join("\n");
  //遍历所有html文件
  for (const file of files) {
    const html = fs.readFileSync(file, "utf-8");
    const root = parse(html);
    //在head中添加
    const head = root.querySelector("head");
    head.insertAdjacentHTML("afterbegin", links);
    fs.writeFileSync(file, root.toString());
  }
}

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

main();

使用:

在package.json的打包命令中添加

javascript 复制代码
 "scripts": {
    "build": "vite build && node ./scripts/dns-prefetch.js",
  },

三、如果是使用webpack打包

这样引入

javascript 复制代码
const fs = require("fs");
const { parse } = require("node-html-parser");
const { glob } = require("glob");
const urlRegex = require("url-regex");
相关推荐
孟祥_成都4 分钟前
深入 Nestjs 底层概念(1):依赖注入和面向切面编程 AOP
前端·node.js·nestjs
let_code4 分钟前
CopilotKit-丝滑连接agent和应用-理论篇
前端·agent·ai编程
z***948414 分钟前
Linux下安装Nginx服务及systemctl方式管理nginx详情
linux·运维·nginx
凉晓风26 分钟前
Linux上TCP通信异常排查工具命令
linux·运维·tcp/ip
Xの哲學27 分钟前
Linux 分区表深度技术剖析
linux·网络·算法·架构·边缘计算
Apifox29 分钟前
Apifox 11 月更新|AI 生成测试用例能力持续升级、JSON Body 自动补全、支持为响应组件添加描述和 Header
前端·后端·测试
木易士心29 分钟前
深入剖析:按下 F5 后,浏览器前端究竟发生了什么?
前端·javascript
在掘金8011031 分钟前
vue3中使用medium-zoom
前端·vue.js
w***42437 分钟前
SQL-Server链接服务器访问Oracle数据
服务器·sql·oracle
孟先生丨42 分钟前
PVE 系统 2.5G网卡驱动从 r8169 切换到 r8125
服务器·5g