Skip to main content

如何统计打开一个网页所用的时间

传统方式一

var t0 = new Date().getTime();
window.onload = function() {
var now = new Date().getTime();
var latency = now -t0;
alert("page loading time: " + latency);
}

传统方式二

var t0 = 135131321312; // 后端输出服务器时间戳
window.onload = function() {
var now = new Date().getTime();
var latency = now -t0;
alert("page loading time: " + latency);
}

传统方式三

**<!-- page1 -->**
<script>
window.onbeforeunload = function() {
var t0 = new Date().getTime();
// 将离开page1页面的时间写入cookie
KISSY.Cookie.set("t0", t0);
}
</script>
**<!-- page2 -->**
<script>
var t0 = KISSY.Cookie.get("t0");
window.onload = function() {
var now = new Date().getTime();
var latency = now -t0;
alert("page loading time: " + latency);
}
</script>

缺点:页面间关联依赖,部署和实现复杂,无法统计直接进入的页面

W3C Navigation Timing API

console.dir(window.performance)

优化原则:尽早返回首字节内容,一部加载页面底部的HTML内容,适量压缩HTML并开启GZIP

将CSS放到页面顶部,优化CSS和JS的顺序,控制DOM Tree数量

一部加载部分静态资源

延迟加载