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");
相关推荐
a小胡哦14 分钟前
Windows、Mac、Linux,到底该怎么选?
linux·windows·macos·操作系统
_extraordinary_24 分钟前
Linux权限(一)
android·linux·excel
易安杰31 分钟前
ElasticSearch+Kibana通过Docker部署到Linux服务器中
linux·elasticsearch·搜索引擎·全文检索·中文分词
web2u36 分钟前
Docker入门及基本概念
java·运维·服务器·spring·docker·容器
MickeyCV41 分钟前
Nginx学习笔记:常用命令&端口占用报错解决&Nginx核心配置文件解读
前端·nginx
祈澈菇凉1 小时前
webpack和grunt以及gulp有什么不同?
前端·webpack·gulp
zy0101011 小时前
HTML列表,表格和表单
前端·html
初辰ge1 小时前
【p-camera-h5】 一款开箱即用的H5相机插件,支持拍照、录像、动态水印与样式高度定制化。
前端·相机
人生!?1 小时前
给小米/红米手机root(工具基本为官方工具)——KernelSU篇
android·linux·智能手机
HugeYLH1 小时前
解决npm问题:错误的代理设置
前端·npm·node.js