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");
相关推荐
持之以恒的天秤1 小时前
线程同步学习
linux·学习
厦门辰迈智慧科技有限公司5 小时前
城市排水管网流量监测系统解决方案
运维·服务器
qq_339282235 小时前
centos中libc.so.6No such file的解决方式
linux·运维·centos
leoufung6 小时前
ECPF 简介
linux·网络·kernel
水银嘻嘻6 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
小嘟嚷ovo6 小时前
h5,原生html,echarts关系网实现
前端·html·echarts
在肯德基吃麻辣烫7 小时前
Netdata在Ubuntu环境下的安装与配置:构建实时系统监控与性能分析平台
linux·运维·ubuntu
十一吖i7 小时前
Vue3项目使用ElDrawer后select方法不生效
前端
只可远观7 小时前
Flutter目录结构介绍、入口、Widget、Center组件、Text组件、MaterialApp组件、Scaffold组件
前端·flutter
周胡杰7 小时前
组件导航 (HMRouter)+flutter项目搭建-混合开发+分栏效果
前端·flutter·华为·harmonyos·鸿蒙·鸿蒙系统