结合 documentfragment 和 Replacechild 以最大程度地减少回流

发布于 2024-12-20 23:16:33 字数 561 浏览 4 评论 0原文

我正在制作一个不使用画布的 JavaScript 游戏,并且我希望屏幕每个周期仅回流一次,以提高速度。有没有办法让 documentFragment 替换命名元素?

编辑: javascript指南建议replaceChild()可以与documentFragment一起使用,但这个例子似乎暗示多次回流:

function reverse(n) {  // Reverses the order of the children of Node n
    var f = document.createDocumentFragment(  ); 
    while(n.lastChild)                 
          f.appendChild(n.lastChild);  
    n.appendChild(f);                  // surely this causes a reflow each time?
}

I'm making a javascript game without using canvas, and I want the screen to reflow only once per cycle, for speed. Is there a way for documentFragment to replace named elements?

EDIT:
The javascript guide suggests that replaceChild( ) can be used with documentFragment but the example seems to imply multiple reflows:

function reverse(n) {  // Reverses the order of the children of Node n
    var f = document.createDocumentFragment(  ); 
    while(n.lastChild)                 
          f.appendChild(n.lastChild);  
    n.appendChild(f);                  // surely this causes a reflow each time?
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹂绝世的画 2024-12-27 23:16:33

如果您将所有内容都放在包装 div 中,它应该可以正常工作。

函数反向...中,最后一行仅执行一次。但是之前的一行(在 while 循环内)将逐一删除元素并每次都会导致回流。

If you put everything in a wrapping div it should work out fine.

In function reverse... the last line is only executed once. But the line before (inside the while loop) will remove elements one by one and cause a reflow each time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文