├── README.md └── index.js /README.md: -------------------------------------------------------------------------------- 1 | ### 首屏渲染时间的计算 2 | > 该文件原本是使用typescript编写,为了方便执行,编译成的JavaScript,因此可能有些地方可读性不太好。 -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var details = [], ignoreEleList = ['script', 'style', 'link', 'br']; 2 | function getFirstScreenTime() { 3 | return new Promise(function (resolve, reject) { 4 | // 5s之内先收集所有的dom变化,并以key(时间戳)、value(dom list)的结构存起来。 5 | var observeDom = new MutationObserver(function (mutations) { 6 | if (!mutations || !mutations.forEach) 7 | return; 8 | var detail = { 9 | time: performance.now(), 10 | roots: [] 11 | }; 12 | mutations.forEach(function (mutation) { 13 | if (!mutation || !mutation.addedNodes || !mutation.addedNodes.forEach) 14 | return; 15 | mutation.addedNodes.forEach(function (ele) { 16 | if (ele.nodeType === 1 && ignoreEleList.indexOf(ele.nodeName.toLocaleLowerCase()) === -1) { 17 | if (!isEleInArray(ele, detail.roots)) { 18 | detail.roots.push(ele); 19 | } 20 | } 21 | }); 22 | }); 23 | if (detail.roots.length) { 24 | details.push(detail); 25 | } 26 | }); 27 | observeDom.observe(document, { 28 | childList: true, 29 | subtree: true 30 | }); 31 | setTimeout(function () { 32 | observeDom.disconnect(); 33 | resolve(details); 34 | }, 5000); 35 | }).then(function (details) { 36 | // 分析上面收集到的数据,返回最终的结果 37 | var result; 38 | details.forEach(function (detail) { 39 | for (var i = 0; i < detail.roots.length; i++) { 40 | if (isInFirstScreen(detail.roots[i])) { 41 | result = detail.time; 42 | break; 43 | } 44 | } 45 | }); 46 | // 遍历当前请求的图片中,如果有开始请求时间在首屏dom渲染期间的,则表明该图片是首屏渲染中的一部分, 47 | // 所以dom渲染时间和图片返回时间中大的为首屏渲染时间 48 | window.performance.getEntriesByType('resource').forEach(function (resource) { 49 | if (resource.initiatorType === 'img' && (resource.fetchStart < result || resource.startTime < result) && resource.responseEnd > result) { 50 | result = resource.responseEnd; 51 | } 52 | }); 53 | return result; 54 | }); 55 | } 56 | function isEleInArray(target, arr) { 57 | if (!target || target === document.documentElement) { 58 | return false; 59 | } 60 | else if (arr.indexOf(target) !== -1) { 61 | return true; 62 | } 63 | else { 64 | return isEleInArray(target.parentElement, arr); 65 | } 66 | } 67 | function isInFirstScreen(target) { 68 | if (!target || !target.getBoundingClientRect) 69 | return false; 70 | var rect = target.getBoundingClientRect(), screenHeight = window.innerHeight, screenWidth = window.innerWidth; 71 | return rect.left >= 0 72 | && rect.left < screenWidth 73 | && rect.top >= 0 74 | && rect.top < screenHeight; 75 | } 76 | --------------------------------------------------------------------------------