When It Makes Sense To “Block” The Main Thread
The common rule of thumb is to never “block” the browser’s main thread when running JavaScript tasks. But is this a hard rule? Victor Ayomipo describes a use case he encountered involving a screenshot extension where he made an exception to the rule and decided that blocking the main thread was absolutely the right thing to do.
We’ve all heard of the sacred rule in modern web development, the rule never to be broken. The rule of “Never block the main thread.” You almost can’t miss it as a web developer; it’s in almost every performance guide, and to be fair, it is good advice. We all know the browser’s main thread is single-threaded , meaning it can only do one thing at a time. Plus, as we know, the main thread isn’t ours alone ; we share it with the browser’s rendering engine, input handlers, and other critical tasks. As a result, the less time we hold onto the main thread, the more responsive an app feels. That leads us to share tasks with background workers as we’ve convinced ourselves there should be a hard line between the UI and any computation, and that line shouldn’t be crossed. And that is what a “recommended” architecture looks like. But I dare say that sometimes**, moving the data to a worker is slower than just letting the main thread do the work. I found this out a few months ago while building a Chrome extension with screenshotting features called Fastary. I kept finding a latency of about 2 to 3 seconds in all my testing, even after using an Offscreen Document (a background process in Chrome extensions) to handle the canvas operations. A screenshot task should feel instant without lag, after all. It is quite ironic that by reflex, we move work away from the main thread to avoid freezing the UI, but sometimes the act of moving that work (e.g., serializing, copying, and deserializing) can also freeze the UI. And sometimes the recommended approach of letting the background do the work can be slower than just doing the work on the main thread. Let’s talk about that. The Architecture Of Browser Context Isolation To put things in perspective, let’s understand why we isolate browser contexts and how they communicate with each other, with emphasis on the communication part. A browser is more than a single environment. Different environments are running at the same time, each having
本文内容来源于互联网,版权归原作者所有
查看原文