在网站和应用程序变的越来越丰富的今天,web应用对网络和设备资源的要求也越来越高。配合各种方式、手段、辅助系统,进行前端优化的最终目的都是提升用户体验,改善页面性能。
我们常常竭尽全力进行前端页面优化,但却忽略了这样做的效果和意义。先不急于探究前端优化具体可以怎样去做,先看看什么是前端性能,应该怎样去了解和评价前端页面的性能。
浏览器API
下图为W3C标准中Performance Timing资源加载和解析过程记录各个关键点的示意图,浏览器中加载和解析一个HTML文件的详细过程先后经历unload、redirect、App Cache、DNS、TCP、Request、Response、Processing、onload几个阶段,每个过程开始和结束的关键时间戳浏览器已经使用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 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| function performanceTest(){
let timing = performance.timing,
readyStart = timing.fetchStart - timing.navigationStart,
redirectTime = timing.redirectEnd - timing.redirectStart,
appcacheTime = timing.domainLookupStart - timing.fetchStart,
unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart,
lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart,
connectTime = timing.connectEnd - timing.connectStart,
requestTime = timing.responseEnd - timing.requestStart,
initDomTreeTime = timing.domInteractive - timing.responseEnd,
domReadyTime = timing.domComplete - timing.domInteractive,
loadEventTime = timing.loadEventEnd - timing.loadEventStart,
loadTime = timing.loadEventEnd - timing.navigationStart;
console.log('准备新页面时间耗时: ' + readyStart);
console.log('redirect 重定向耗时: ' + redirectTime);
console.log('Appcache 耗时: ' + appcacheTime);
console.log('unload 前文档耗时: ' + unloadEventTime);
console.log('DNS 查询耗时: ' + lookupDomainTime);
console.log('TCP连接耗时: ' + connectTime);
console.log('request请求耗时: ' + requestTime);
console.log('请求完毕至DOM加载: ' + initDomTreeTime);
console.log('解析DOM树耗时: ' + domReadyTime);
console.log('load事件耗时: ' + loadEventTime);
console.log('加载时间耗时: ' + loadTime); }
|
Navigation Timing
Resource Timing
页面埋点计时
使用new Date()时间戳记录操作的时间点
工具
Profile工具
原文:
前端性能分析
谷歌性能优化文章