function firstScreen() {
// 收集所有页面的加载时间
const imgs = document.getElementsByTagName('img')
const fsItems = []
const loadEvent = function() {
// gif避免
if (this.removeEventListener) {
this.removeEventListener('load', loadEvent, false)
}
const curTime = +new Date()
fsItems.push({
img: this,
time: curTime
})
}
for (let i = 0; i < imgs.length; i++) {
(function() {
const img = imgs[i]
if (img.addEventListener) {
!img.complete && img.addEventListener('load', loadEvent, false)
} else if (img.attachEvent) {
img.attachEvent('onreadystatechange', function() {
if (img.readyState == 'complete') {
loadEvent.call(img, loadEvent)
}
})
}
})()
}
// 获取元素在dom中的位置
function getOffsetTop(elem) {
let top = 0
top = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop
top += elem.getBoundingClientRect().top
return top
}
function findMaxTime() {
const sh = document.documentElement.clientHeight
let maxTime = 0
for (var i = 0; i < fsItems.length; i++) {
var item = fsItems[i]
var img = item['img']
var time = item['time']
var top = getOffsetTop(img)
if (top > 0 && top < sh) { // 找首屏中的图片
maxTime = time > maxTime ? time : maxTime
}
}
return maxTime
}
window.addEventListener('load', function() {
const imgTime = findMaxTime()
const domTime = window.performance.timing.domInteractive // dom完成时间
let speedTime
const startTime = window.performance.timing.navigationStart || window.performance.timing.startTime // 页面首页时间
const screenTime = imgTime > 0 ? imgTime : domTime // 如果没有图片,直接取dom时间
// eslint-disable-next-line prefer-const
speedTime = screenTime - startTime
console.log(speedTime)
})
}
firstScreen()
直接放到main.js最下方执行即可