如何测试DNS预获取和预连接的效果?

22
我正在尝试使用 <link rel="dns-prefetch"><link rel="preconnect"> 标签,并尝试查看它们是否对我的网站有所帮助。我无法找到任何关于如何使用浏览器开发工具、扩展程序或其他软件来验证这些提示是否有效的在线资源。似乎你只是根据一些标准评估它们是否有用,然后放置它们,并期望最好的结果。
在我的情况下,我有一个单页应用程序,在浏览器中呈现整个 <body> 内容,所以浏览器无法真正扫描初始 HTML 来预先查找要解析的域名,所以这对我可能是有用的。

你需要找到一种方法来测试服务器多次(1000次),并使用优化和未经优化的数据统计计算瀑布数据。这应该针对每种浏览器类型(FF,Chrome,IE,Safari等)进行重复。我不知道有这样的工具... - vsync
略有关联:https://dev59.com/MYPba4cB1Zd3GeqPv7ev - jakub.g
3个回答

10

为了确保某个浏览器支持特定功能(进行简单的测试),您可以按照以下步骤操作

测试 1:在 Chrome 中测试 dns-prefetch (仅 DNS)

  • serve the following HTML on localhost

    <!doctype html><html><head>
        <link rel="dns-prefetch" href="//ajax.googleapis.com">
    </head><body></html>
    
  • go to chrome://net-internals/#dns and clear host cache

  • open new tab in Chrome on http://localhost
  • refresh chrome://net-internals/#dns and observe it to have the DNS entry - this confirms that DNS resolution has been done

测试2:使用Chrome和Fiddler(仅限Windows)测试preconnect(DNS+TLS+TCP)

  • serve the following HTML on localhost

    <!doctype html><html><head>
        <link rel="preconnect" href="https://ajax.googleapis.com">
    </head><body></html>
    
  • go to chrome://net-internals/#dns and clear host cache

  • start Fiddler and make it listen to the traffic
  • open new tab in Chrome on http://localhost
  • observe Fiddler to have a "Tunnel to ajax.googleapis.com:443" session - this confirms that DNS resolution and TLS handshake were done (and you can probably trust the browser that it established a TCP connection too)

测试1的示例HTML也是rel="preconnect",应该改为"dns-prefetch" :) - Null
1
在chrome://net-internals/#dns中没有看到任何DNS条目,尽管有Host解析器缓存选项。 - Abhinav Singi

9

将您的网页通过webpagetest.org进行测试。由于已建立初始连接,因此对于您在dns-prefetch或preconnect标记中指定的域的请求,应该会更早地开始。

这将显示在瀑布图中,对于那些请求-在条形图的左侧,DNS连接和SSL(如果适用)段将从响应中分离并向左移动,以反映它们发生的时间较早。


2
有没有办法在本地测试它?谢谢。 - Jonathan Dion

3
为了以一种非常细粒度和可自定义的方式测试DNS时间的影响,这里有另一种方法:解析HAR文件。
在打开网络面板的情况下加载网站,然后下载HAR文件
将该HAR文件作为JSON读入(可以使用Node中的readFile或浏览器中的FileReader),您将得到一个像这样的对象:
const har = {
  log: {
    version: {},
    creator: {},
    page: {},
    entries: {}, // <-- You want these
  }
}

然后你可以查看(并进行数学运算)har.log.entries[idx].timing.dns,这样你就可以回答以下问题:
等待 DNS 获取共花费了多少时间?
const ms = har.log.entries.map(e => e.timing.dns).reduce(sum); // NOTE: should rm all the -1s
console.log('Total DNS Time: ' + ms);

// Total DNS Time: 242 ms

哪些请求完全等待DNS?
const display = har.log.entries
  .filter(e => dnsTime(e) > 0)
  .map(e => ({
      method: e.request.method,
      url: e.request.url,
      dns: dnsTime(e),
    })
  );

console.table(display);
// Prints a nice table with things like: [GET foo.com 72ms]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接