一个 web App 的响应时间对用户体验的影响是非常大的
对于资源加载时间的统计有利于我们找出影响加载时间因素并进行优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script> if ( !('performance' in window) || !('timing' in window.performance)) { console.log('not support window.performance') } else { window.addEventListener('load', function() { var t = window.performance.timing var perfSrc = 'http://www.xxx.com/perf.gif?' for (var key of t) { if (typeof(t[key]) === 'number') perfSrc += key + '=' + t[key] + '&' } var perf = document.createElement('img') perf.style.cssText = 'width: 0; height: 0; position: absolute;' perf.src = perfSrc document.body.appendChild(perf) }); } </script>
|
Browser Support
首先是对 Navigation Timing API 的浏览器支持情况进行检测
Get timing
如果浏览器支持的话,在 window load 的时候
获取 performance.timing 的相关属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| { connectEnd: 1533624540751 connectStart: 1533624540726 domComplete: 1533624541675 domContentLoadedEventEnd: 1533624541492 domContentLoadedEventStart: 1533624541488 domInteractive: 1533624541488 domLoading: 1533624540862 domainLookupEnd: 1533624540726 domainLookupStart: 1533624540726 fetchStart: 1533624540723 loadEventEnd: 1533624541676 loadEventStart: 1533624541675 navigationStart: 1533624540713 redirectEnd: 0 redirectStart: 0 requestStart: 1533624540754 responseEnd: 1533624540865 responseStart: 1533624540855 secureConnectionStart: 1533624540730 unloadEventEnd: 0 unloadEventStart: 0 }
|
这些属性对应的时间点如下图:
Send Request
最后,发送一个(图片)请求将性能数据发送到服务器