Authored by 毕凯

增加首屏检测

var cookies = require('./cookie');
// 首屏时间尝试:
// 1,获取首屏基线高度
// 2,计算出基线dom元素之上的所有图片元素
// 3,所有图片onload之后为首屏显示时间
// 参考 https://www.zhihu.com/question/23212408/answer/56647975
//
function getOffsetTop(ele) {
var offsetTop = ele.offsetTop;
if (ele.offsetParent !== null) {
offsetTop += getOffsetTop(ele.offsetParent);
}
return offsetTop;
}
var firstScreenHeight = window.screen.height;
var firstScreenImgs = [];
var isFindLastImg = false;
var allImgLoaded = false;
var firstScreenLoadTime = 0;
var t = setInterval(function() {
var i, img;
if (isFindLastImg) {
if (firstScreenImgs.length) {
for (i = 0; i < firstScreenImgs.length; i++) {
img = firstScreenImgs[i];
if (!img.complete) {
allImgLoaded = false;
break;
} else {
allImgLoaded = true;
}
}
} else {
allImgLoaded = true;
}
if (allImgLoaded) {
firstScreenLoadTime = (new Date()).getTime() - _timeStart
clearInterval(t);
}
} else {
var imgs = document.body.querySelector('img');
for (i = 0; i < imgs.length; i++) {
img = imgs[i];
var imgOffsetTop = getOffsetTop(img);
if (imgOffsetTop > firstScreenHeight) {
isFindLastImg = true;
break;
} else if (imgOffsetTop <= firstScreenHeight && !img.hasPushed) {
img.hasPushed = 1;
firstScreenImgs.push(img);
}
}
}
}, 0);
var reporter = {
config: {
reportUrl: '//analytics.m.yohobuy.com/yas.gif',
... ... @@ -64,7 +120,7 @@ var reporter = {
var self = this;
var errorList = JSON.parse(cookies(this.config.errorKey) || '[]');
var errStr = this.stringify(errorList);
this.report(errStr, function() {
self.clearError();
})
... ... @@ -84,22 +140,40 @@ var reporter = {
document.addEventListener && document.addEventListener('DOMContentLoaded', function(event) {
timeList.push({
tp: 'dcl', // DOMContentLoaded
t: (new Date()) - _timeStart
t: (new Date()).getTime() - _timeStart
});
// 首屏加载速度
var imgs = document.body.querySelector('img');
if (!imgs.length) {
isFindLastImg = true;
}
})
window.addEventListener && window.addEventListener('load', function(event) {
timeList.push({
tp: 'ld', // load
t: (new Date()) - _timeStart
t: (new Date()).getTime() - _timeStart
});
// 首屏加载速度
allImgLoaded = true;
isFindLastImg = true;
if (t) {
clearInterval(t);
}
if (firstScreenLoadTime) {
timeList.push({
tp: 'fs', // firstScreenLoadTime
t: firstScreenLoadTime
});
}
timeList.push({
tp: 'pf', // performance
dcl: (window.performance && window.performance.timing.domComplete || 0) - pStart,
ld: (window.performance && window.performance.timing.loadEventStart || 0) - pStart
});
self.reportTime(timeList); // 先上报 DOMContentLoaded,load 的时间
});
... ...