如何使用JS操纵DOM而不阻止网页? [英] How to manipulate DOM with JS without blocking the webpage?

查看:287
本文介绍了如何使用JS操纵DOM而不阻止网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用JS来操作DOM。操纵过程需要很多时间。
如何做到这一点不会阻止网页?
用户应该能够同时使用该网页。

解决方案

您可以批量进行。在每个批处理结束时,使用短暂的超时时间,使用 setTimeout 进行下一个批处理浏览器刷新显示,处理事件等的机会。



此外,如果您执行一个需要很长时间的操作,因为它必须等待某些速度慢(如网络请求),一旦数据可用就可以通过回调开始,以非阻塞的方式执行。轮询不放弃CPU将使浏览器认为脚本不再响应,并询问用户是否要终止它。


I need to manipulate DOM with JS. The manipulation process takes a lot of time. How can I do this not blocking the webpage? The user should be able to use the webpage in the meanwhile.

解决方案

You can do it in batches. At the end of each batch schedule the next batch with setTimeout using a short timeout to give the browser a chance to refresh the display, process events etc.

Also, if you do an operation that takes long because it has to wait for something slow (like a network request), do it it a non-blocking manner by starting via a callback as soon as the data is available. Polling without relinquishing CPU will make the browser think the script is no longer responding and ask the user if he wants to terminate it.

这篇关于如何使用JS操纵DOM而不阻止网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆