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");
相关推荐
Zfox_1 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
apocelipes5 小时前
Linux c 运行时获取动态库所在路径
linux·c语言·linux编程
ABB自动化5 小时前
for AC500 PLCs 3ADR025003M9903的安全说明
服务器·安全·机器人
coding随想5 小时前
JavaScript ES6 解构:优雅提取数据的艺术
前端·javascript·es6
努力学习的小廉6 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
小小小小宇6 小时前
一个小小的柯里化函数
前端
灵感__idea6 小时前
JavaScript高级程序设计(第5版):无处不在的集合
前端·javascript·程序员
小小小小宇6 小时前
前端双Token机制无感刷新
前端
小小小小宇6 小时前
重提React闭包陷阱
前端
秃头菜狗6 小时前
各个主要目录的功能 / Linux 常见指令
linux·运维·服务器