DOM节点统计

DOM 的体积过大会影响页面性能,
	假如你想在用户关闭页面时统计(计算并反馈给服务器)
	当前页面中元素节点的数量总和、元素节点的最大嵌套深度以及最大子元素个数,
	请用 JS 配合原生 DOM API 实现该需求
	(不用考虑陈旧浏览器以及在现代浏览器中的兼容性,可以使用任意浏览器的最新特性;不用考虑 shadow DOM
<html>
  <head></head>
  <body>
    <div>
      <span>f</span>
      <span>o</span>
      <span>o</span>
    </div>
  </body>
</html>
  class Ele {
    constructor(ele) {
      this.ele = ele;
      this.depthNum = 1;
    }
    // 获取当前节点的元素深度
    getEleDepth() {
      let parentNode = this.ele.parentNode;
      if (parentNode !== document) {
        this.depthNum++;
        this.ele = parentNode;
        return this.getEleDepth();
      } else {
        return this.depthNum;
      }
    }
    // 获取当前节点的子元素个数
    getEleSubNum() {
      let childNodes = this.ele.childNodes;
      let childNum = 0;
      for (let i = 0; i < childNodes.length; i++) {
        if (childNodes[i].nodeName !== '#text') {
          childNum++;
        }
      }
      return childNum;
    }
  }


  function domInfo(dom) {
    let totalElementsCount = 0; // 最大子元素个数
    totalElementsCount = dom.length; //dom中的所有节点数量
    let eleDepthArr = [];
    let eleSubArr = [];
    for (let i = 0; i < totalElements.length; i++) {
      eleDepthArr.push(new Ele(totalElements[i]).getEleDepth());
      eleSubArr.push(new Ele(totalElements[i]).getEleSubNum());
    }
    eleDepthArr = eleDepthArr.sort((a, b) => b - a); // 最大嵌套深度
    eleSubArr = eleSubArr.sort((a, b) => b - a); // 最大子元素个数
    return {
      totalElementsCount:totalElementsCount,
      maxDOMTreeDepth:eleDepthArr[0],
      maxChildrenCount:eleSubArr[0]
    }
  }
  const totalElements = document.getElementsByTagName('*');
  let obj = domInfo(totalElements)
  console.log(obj);
最简单的百度一下
	maxChildrenCount: 41
	maxDOMTreeDepth: 13
	totalElementsCount: 247

你可能感兴趣的:(Javascript,DOM,Exercises,javascript,html,html5,typescript,前端)