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

使用 TreeWalker 遍历 DOM nodes? #10

Open
mozbugbox opened this issue Jan 31, 2020 · 2 comments
Open

使用 TreeWalker 遍历 DOM nodes? #10

mozbugbox opened this issue Jan 31, 2020 · 2 comments

Comments

@mozbugbox
Copy link
Contributor

现在自动生成的页面有越来越多的node, 通过递归函数遍历DOM会占用大量堆栈,而且也影响速度。可以试试使用 TreeWalker 看看是否会加快速度,减少运存使用量。

@chitosai
Copy link
Owner

chitosai commented Oct 1, 2022

来自3年后的回复,抱歉回复晚了一(hen)点(jiu)😅

今天终于是看了下文档,但我们是需要递归的,因为父元素有时会决定子元素是否需要继续遍历,或者是遍历的时候是否需要做特殊处理。所以好像没办法发挥TreeWalker的优势?

@mozbugbox
Copy link
Contributor Author

可以考虑不直接使用 nextNode(), 而是通过使用 firstChild/nextSibling/parentNodenextSibling() 的组合手动进行 deep first 的遍历,应该可以把父元素不断的 push/pop 到一个数组里。这样就可以访问父祖元素了。

类似:

parents = []
node = root
goUp = false
while (true) {
    if (goUp) {
        goUp = false
        node = walker.parentNode()
        if (!node) {
            break;
        } else {
            parents.pop()
            node = walker.nextSibling()
            if (!node) {
                goUp = true 
                continue
            }
        }
    } else {
        node = walker.firstChild()
        if (!node) {
            node = walker.nextSibling()
            if (!node) {
                goUp = true;
                continue
            } 
        } else { 
            parents.push(node.parentNode)
        }
    }
}

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

2 participants