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

一、优化原理

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

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

2.为什么需要优化

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

3.优化思路

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

优化前流程图:

在解析过程中每当遇见外部资源时就会产生短暂阻塞影响页面加载

优化后流程图:

在开始解析HTML后异步预解析DNS,当后续需要使用时,已经解析了一部分或者已经解析好,节省了解析时间

二、代码实现

需要安装的包:

npm install node-html-parser

npm install glob

npm install url-regex

dns-prefecth.js:

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的打包命令中添加

 "scripts": {
    "build": "vite build && node ./scripts/dns-prefetch.js",
  },

三、如果是使用webpack打包

这样引入

const fs = require("fs");
const { parse } = require("node-html-parser");
const { glob } = require("glob");
const urlRegex = require("url-regex");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值