Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

20190509-001.md #1

Open
homobulla opened this issue May 9, 2019 · 0 comments
Open

20190509-001.md #1

homobulla opened this issue May 9, 2019 · 0 comments

Comments

@homobulla
Copy link
Owner

homobulla commented May 9, 2019

question

DOM 的体积过大会影响页面性能,假如你想在用户关闭页面时统计(计算并反馈给服务器)当前页面中元素节点的数量总和、多少种HTML标签种类、元素节点的最大嵌套深度以及最大子元素个数,请用 JS 配合原生 DOM API 实现该需求(不用考虑陈旧浏览器以及在现代浏览器中的兼容性,可以使用任意浏览器的最新特性;不用考虑 shadow DOM)。

 let maxChildrenCount = 0, // 元素节点的总和
     maxDOMTreeDepth = 0, //元素最大嵌套问题
     totalElementsCount = 1, //最大子元素
     totalDOMTypeCount = new Set([...document.getElementsByTagName("*")].map(x=>x.tagName)).size; //DOM种类
    function DFS(e, depth) {
        // 没有子节点了, 意味着 DFS 已经抵达一个叶节点, 更新深度计数器
        if (e.children.length === 0) {
            maxDOMTreeDepth = depth > maxDOMTreeDepth ? depth : maxDOMTreeDepth;
            return;
        }
        let stack = Array.from(e.children) 
        stack.forEach(n => {
            // 更新总标签数
            totalElementsCount += 1;
            // 更新最大子元素数
            if (stack.length > maxChildrenCount) maxChildrenCount = stack.length;
            DFS(n, depth + 1);
        });
    }
    DFS(document.querySelector("html"), 1);
    console.log({
        totalElementsCount,
        maxDOMTreeDepth,
        maxChildrenCount,
        totalDOMTypeCount 
    });

extend

如何获取页面中出现次数最多的元素及其出现次数?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant