Posts MutationObserver计算FMP
Post
Cancel

MutationObserver计算FMP

  • FMP 即 First Meaningful Paint,有意义的首屏时间
  • 通过 MutationObserver 观察 DOM 结构变化以及视口范围计算实现

实现方案

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const details = [];
const ignoreEleList = ['script', 'style', 'link', 'br'];
let observeDom;
let firstScreenTiming;

// 查看当前元素的祖先元素是否在数组中
function isEleInArray(target, arr) {
  if (!target || target === document.documentElement) {
    return false;
  } else if (arr.indexOf(target) !== -1) {
    return true;
  } else {
    return isEleInArray(target.parentElement, arr);
  }
}

function isInFirstScreen(target) {
  if (!target || !target.getBoundingClientRect) return false;

  const rect = target.getBoundingClientRect();
  const screenHeight = window.innerHeight;
  const screenWidth = window.innerWidth;
  return rect.left >= 0
    && rect.left < screenWidth
    && rect.top >= 0
    && rect.top < screenHeight;
}

function updateTiming() {
  if (observeDom) {
    observeDom.disconnect();
  }
  for (let i = 0; i < details.length; i++) {
    const detail = details[i]
    for (let j = 0; j < detail.roots.length; j++) {
      if (isInFirstScreen(detail.roots[j])) {
        firstScreenTiming = detail.time;
        break;
      }
    }
    if (typeof firstScreenTiming === 'number') {
      break;
    }
  }
  console.log('ccc firstScreenTiming', firstScreenTiming);
}

if (window.MutationObserver) {
  observeDom = new MutationObserver((mutations => {
    if (!mutations || !mutations.forEach) return;
    const detail = {
      time: performance.now(),
      roots: [],
    };

    mutations.forEach(mutation => {
      if (!mutation || !mutation.addedNodes || !mutation.addedNodes.forEach) return;

      mutation.addedNodes.forEach(ele => {
        if (ele.nodeType === 1 && ignoreEleList.indexOf(ele.nodeName.toLocaleLowerCase()) === -1) {
          if (!isEleInArray(ele, detail.roots)) {
            detail.roots.push(ele);
          }
        }
      });
    });

    if (detail.roots.length) {
      details.push(detail);
    }
  }));

  observeDom.observe(document, {
    childList: true,
    subtree: true,
  });
}

window.addEventListener('load', function () {
  updateTiming()
});

效果

01.png

由图可见,页面是 Node 直出,在页面 DOM 元素开始渲染的时候会触发 MutationObserver 事件,即可获取到渲染事件。

This post is licensed under CC BY 4.0 by the author.
Trending Tags
Contents

Trending Tags