#前端 #优质博文 #javascript #性能优化
There are a lot of ways to break up long tasks in JavaScript.
有很多方法可以在JavaScript中分解长任务
via Alex MacArthur
There are a lot of ways to break up long tasks in JavaScript.
有很多方法可以在JavaScript中分解长任务
AI 摘要:这篇文章讨论了长任务(Long Tasks)对网页性能的影响,以及如何优化用户体验。长任务是指执行时间超过 50ms 的 JavaScript 任务,会阻塞主线程,导致页面卡顿,影响交互响应。文章介绍了如何使用Performance API识别长任务,并提出了优化策略,如将任务拆分成更小的部分 (如使用setTimeout
、requestIdleCallback
)、 Web Workers以及避免不必要的重排和重绘。此外,作者还提供了一些实用工具,如 Chrome DevTools,用于分析和优化长任务,以提升页面的流畅度和响应速度。
我们在这里介绍的方法并不详尽,但我认为这些方法很好地体现了在分解长任务时应该考虑的各种权衡。不过,根据需要,我自己可能只会采用其中的一个子集。
If I can do the work off from the main thread, I'd choose a web worker, hands-down. They're very well supported across browsers, and their entire purpose is to offload work from the main thread. The only downside is their clunky API, but that's eased by tools like Workerize and Vite's built-in worker imports.
如果能从主线程中卸载工作,我会毫不犹豫地选择网络 Worker。网络 Worker 在各种浏览器中都得到了很好的支持,而且它们的全部目的就是从主线程中卸载工作。唯一的缺点是 API 比较笨拙,但 Workerize 和 Vite 内置 Worker 导入等工具可以缓解这一问题。
If I need a dead-simple way to break up tasks, I'd go for scheduler.yield(). I don't love how I'd also need to polyfill it for non-Chromium users, but the majority of people would benefit from it, so I'm up for that extra bit of baggage.
如果我需要一个简单的方法来分解任务,我会选择 scheduler.yield()。我不喜欢还需要为非 Chromium 用户 polyfill 它,但大多数人都会从中受益,所以我愿意承受额外的负担。
If I need very fine-grained control over how chunked work is prioritized, scheduler.postTask() would be my choice. It's impressive how deep you can go in tailoring that thing to your needs. Priority control, delays, cancelling tasks, and more are all included in this API, even if, like .yield(), it needs to be polyfilled for now.
如果我需要非常细粒度的控制工作优先级,那么scheduler.postTask()将是我的选择。令人印象深刻的是,您可以为您的需求量身定制这种东西多么深刻。优先控制,延迟,取消任务以及更多内容都包含在此API中,即使现在.yield()它需要暂时进行polyfilled。
If browser support and reliability are of the utmost importance, I'd just choose setTimeout(). It's a legend that's not going anywhere, even as flashy alternatives hit the scene.
如果浏览器支持和可靠性至关重要,我只选择setTimeout() ,它是一个不会消失的传奇,即使华而不实的替代品层出不穷。
via Alex MacArthur