通过Javascript引起的改变的渲染时间测量

5

我希望能够测量由JavaScript实际完成的DOM更改直到其显示所需的时间。

考虑这个示例SVG文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   width="1600"
   height="1000"
   version="1.1">
  <script xlink:href="clicktest.js" />
  <defs>
    <filter id="filterBlur" x="-0.6" width="2.2" y="-0.6" height="2.2">
      <feGaussianBlur stdDeviation="120" />
    </filter>
  </defs>
  <rect y="50" x="50" height="100" width="200" style="fill:#ff0000" onmousedown="red()" />
  <rect y="50" x="300" height="100" width="200" style="fill:#0000ff" onmousedown="blue()" />
  <circle cx="800" cy="600" r="300"  id="circle"
          style="fill:#888888;filter:url(#filterBlur)" />
  <text id="time" x="1250" y="50" style="font-size:40px">time...</text>
  <rect x="900" y="300" width="600" height="600"
        style="fill:#650088;fill-opacity:0.5;filter:url(#filterBlur)" />
  <rect x="100" y="400" width="300" height="400"
        style="fill:#999900;fill-opacity:0.5;filter:url(#filterBlur)" />
</svg>

这段代码展示了两个rect,它们充当“按钮”,可以改变圆形的颜色。额外的rect、模糊和透明度是为了使其更加缓慢。
脚本如下:
function blue()
{
  var startTime = performance.now();
  document.getElementById('circle').style.fill = '#0000ff';
  var endTime = performance.now();
  document.getElementById('time').textContent = (endTime - startTime).toString();
}

function red()
{
  var startTime = performance.now();
  document.getElementById('circle').style.fill = '#ff0000';
  var endTime = performance.now();
  document.getElementById('time').textContent = (endTime - startTime).toString();
}

现在点击时,会显示少于1毫秒的时间,但实际上需要接近一秒钟(在我的电脑上)才能真正显示改变后的颜色(顺便说一句,在这方面Chrome似乎比Firefox更快)。

我如何测量从点击开始到渲染完成结束的时间?


1
在这种情况下,“requestanimationframe”很可能会成为您的好朋友。 - Ben Aston
@Ben:谢谢!这似乎在Chrome和Opera上可以工作,但在FF或IE上根本不行。有什么提示吗? - Martin
无法使用网页中的JavaScript来测量这个。需要使用某种插件或浏览器提供的工具集来完成。 - Robert Longson
1个回答

1

1.打开Chrome(空白页)
2.打开DevTools(F12)
3.切换到“时间轴”选项卡
4.点击录制
5.在Chrome中粘贴您的URL并按回车键
6.等待页面完全加载
7.停止录制
我认为您会在那里找到答案。

这是Chrome时间轴上您源结果的示例:

enter image description here

编辑:有关JavaScript执行和结果呈现时间的更多详细信息,您可以使用“DynaTrace”或“SpeedTracer”(使用这些工具的外观如此处所示)


适用于 Chrome 和 Opera。然而,当然不能使用它来测量使用 JavaScript 的渲染时间。 - Martin

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