❌

Vue normale

When It Makes Sense To “Block” The Main Thread

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 its own memory space, what it can access, and rules:

  • The main thread is what we are most familiar with; this is where JavaScript logic runs, where the DOM lives, where styles get rendered, and where users interact.
  • The Web Workers are separate threads that can also execute JavaScript without DOM access. We mostly use this for heavy data tasks.
  • The Service Workers are network-related proxies in charge of intercepting network requests and can even run when the page is closed.
  • And then there are Chrome extension contexts, where we have background service workers, content scripts, and Offscreen Documents (the relevant ones for this article).

Each one of these is isolated from the others. A web worker or background script lives in a different memory space from the main thread. They cannot just reach and read each other’s variables or logic, and this is known as the “shared-nothing” architecture.

How do these isolated environments communicate? They explicitly message each other back and forth using APIs, like postMessage().

The Structured Clone Algorithm

postMessage() tells the browser to take a piece of data and deliver it to the context that requested it. But to do this, the browser relies on the Structured Clone Algorithm (SCA).

You’re probably familiar with JSON.stringify(). SCA is similar, but much stronger and smarter. In its simplest form, SCA is a deep, recursive copy operation, i.e., cloning. It walks through the entire data structure it is given, clones every single value, serializes it into a transportable format, ships those bytes to the target contexts, and then reconstructs the original object on the receiving side.

SCA is fast, or maybe fast-ish... For a small regular config object like {theme: "dark"}, it is imperceptible; you don’t even notice it. The story changes, however, when dealing with heavy data because the SCA is a synchronous blocking O(n) operation, i.e., the cost increases linearly with the size of your data.

Let’s put that into perspective. A user clicks a button, and internally, an 8MB image payload is sent to a background worker for processing. When you call postMessage(), the main thread must immediately stop what it is doing to run this serialization and copying process.

So, if the time it takes to pack, ship, unpack the data, and go back to the start is longer than the time to just process the data on the main thread, why not do that instead?
What About Transferable Objects?

I’m sure some of you are already thinking, “Why not just use Transferable objects?” And that is a valid point. Let’s talk about that.

Developers who really pursue ultra-high-performance web apps usually use Transferable objects (e.g., ArrayBuffer, ImageBitmap, or MessagePort) to bypass the Structured Clone Algorithm. This is because when you transfer an object, you’re not making a copy (like SCM). Instead, the browser switches ownership of the data from one context to another.

The browser performs a hand-off whereby the sending context loses access to the data instantly, and the receiving context takes full control. It is actually insanely fast. According to Chrome Developers’ benchmark, transferring a massive 32MB ArrayBuffer can take under 7ms, compared to about 300ms when cloning with SCM. That’s a 43x speed boost.

But like all good things, there are downsides. To name a few:

  • You lose it once you send it.
    If the UI still needs that data (like to show an image preview), you can’t access it anymore.
  • Not all data is transferable.
    A plain JS object is not. A Blob is not. Even a Base64 string is not.
  • API limitations.
    In the context of browser extensions, Chrome’s internal messaging (chrome.runtime.sendMessage) traditionally forces everything through JSON serialization.

So, as far as my screenshot extension went, Transferable objects were not an option.

Why We Isolate Contexts Anyway

Why do we even bother isolating contexts at all? Why not just leave it all to the main thread?

Offloading long-running CPU tasks to a background thread is absolutely the right thing to do. The browser needs to paint a new frame every 16.6ms to keep things fluid; that means any task that takes >50ms is generally considered “long”. Offloading to the background is absolutely the right thing to do.

The issue, however, is that we’ve turned this “never block the main thread” into an absolute rule, without asking is this task expensive to process or expensive to move?

I have come to realize now that the rule is less “never block the main thread” than “never block the main thread for too long.”

When The Right Architecture Is The Wrong Architecture

My goal with the Fastary extension was to make it feel like a native app, running as smoothly and instantly as you would expect a native app to.

As you already know, I took the recommended approach to use the Offscreen Document to handle DOM work in the background. But to my surprise, that took a different turn.

The Offscreen Document API is a clear winner. You create a hidden, undisplayed document that runs entirely in the background. It has a DOM and supports Canvas. For example, if I want to crop a screenshot, stitch multiple screenshots together, perform heavy image manipulation, or add a watermark, Offscreen Document was made for that.

Turns out that was not the best approach. This was my architecture:

  1. The background Service Worker captures a screenshot with chrome.tabs.captureVisibleTab(), which returns a Base64-encoded data URL string.
  2. The background Service Worker uses chrome.runtime.sendMessage() to ship this image payload to the Offscreen Document.
  3. The Offscreen Document receives the image, loads it into an <img> element, then draws it onto a canvas before it applies the user’s crop coordinates, encodes the result, and sends the processed image back to the background worker.

But when I tested it, the screenshot didn’t feel instant. As I said earlier, there was a consistent 2–3 second lag.

I figured out that when captureVisibleTab() takes a screenshot, it returns a Base64 URL string, and on a standard 1080p screen, that string could be approximately 1MB or more, depending on how detailed the image is. It gets even more interesting on modern Retina displays (e.g., MacBooks) as they tend to automatically double the image’s size by default.

Keep in mind that since the image payload could be doubled and extension messaging relies on JSON serialization (as of this writing), we potentially deal with massive synchronous communication that costs an entire round trip.

The image string data is JSON-serialized at least twice: once when going into the Offscreen Document and once coming back out with the processed results to the background worker. The actual image processing (cropping) done inside the Offscreen Document was fast, no doubt, but I can’t say the same about the transfer overhead.

The Retina High-DPI Problem

As if the latency itself wasn’t enough, I noticed a rather subtle bug — which, now that I think of it, was more of my ignorance. After a screenshot was taken, the crop result was completely off in a way that either weirdly scaled the image or resulted in incorrect coordinates.

It turns out that when a user selects a region to crop, the content script gets the box coordinates using getBoundingClientRect(), which is measured in CSS pixels; this is what the DOM uses. But when the screenshot is captured natively in Chrome, the browser doesn’t crop it automatically; it instead uses the physical hardware pixels to get the full screen capture. And the browser uses devicePixelRatio (DPR) to know how many physical pixels should represent one CSS pixel. Basically, if a user on a Retinal display (DPR = 2) highlights an area of 400x300 CSS pixels, the actual captured image area is 800x600 physical pixels.

Note: One CSS pixel is equal to 1 physical pixel (DPR of 1) on a standard monitor. On a Mac Retina display or a modern 4K monitor, however, the DPR is usually 2 or 3.

For an accurate crop, I needed to apply these two different measurement systems with the right DPR, i.e., scale the crop coordinates by the DPR. But remember, Offscreen Documents have no physical display. Processing any image would have a default DPR equal to 1. To fix this, I would have to capture the exact devicePixelRatio from the active tab, serialize it, pass it alongside the image payload, and manually do the scaling math inside the Offscreen Document. The complexity starts to compound.

What if I broke the golden rule and did the work on the main thread instead?

Working On The Main Thread

Some developers will argue that UI tasks are the only things that should run on the main thread, but I don’t fully agree with that. Personally, I believe that user explicitly-invoked actions that need immediate results can sometimes get a solid pass to run on the main thread, provided the work is incredibly fast (e.g., 1s).

That’s what I did: scrap out the Offscreen Document and reengineer the logic. Instead of:

Background → [serialize] → Offscreen Document → [serialize] → Background → Content Script

…I decided to run the whole image processing in the active tab:

  1. The background Service Worker captures the screen and gets the Base64 string (same as before).
  2. The background sends the payload directly to the content script in the active tab using chrome.scripting.executeScript().
  3. The content script (running on the main thread) receives the payload, draws it to a canvas, performs the crop using the correct DPR value, and copies the result to the clipboard.
// Background Script
const screenshotUrl = await chrome.tabs.captureVisibleTab(undefined, { format: "png" });

// Inject the processing function into the active tab as a content script
await chrome.scripting.executeScript({
  target: { tabId: activeTab.id },
  func: processAndCopyImage,
  args: [{ base64Image: screenshotUrl, cropData: userSelection }]
});

This approach completely clears out multiple context hops and round trips that JSON serialization requires. The only cross-context transfer involves sending the data URL from the background to the content script.

The Retina DPI issue essentially solved itself, as the content script runs directly inside the real, active browser tab because it knows the monitor’s real devicePixelRatio.

But there’s an elephant in the room that you may have noticed.

Sure, the image is now processed on the main thread, and the background manipulates the canvas in the active tab. I could technically be blocking the main thread. That’s where I amended the “no blocking the main thread” rule to “no blocking the main thread for too long.” In this specific case, at least, blocking the main thread for a task the user requests for approximately one second is justifiable. It works conversely as well: maybe don’t isolate processes if the data transfer cost is greater than the processing cost.

Conclusion: When To Isolate And When Not To

I’ve boiled it down to a mental model that depends on whether the task is:

1. Compute-Heavy Tasks (CPU-Bound)

These are tasks where the primary cost is computation and not the size of the data itself. These are tasks where most of the time is spent on doing calculations or heavy transformations, e.g., image compression, audio profiling, physics simulation, etc.

The transfer cost for these tasks is minuscule compared to the actual work.

2. Data-Heavy Tasks (Data-Bound)

These tasks are the exact opposite. These tasks are only expensive because of the size. The processing time is almost insignificant, but the data is expensive to transport, e.g., image cropping, filtering an array, shallow copy, etc.

In my specific case, offloading the task to the background falls mostly into negative-sum efficiency. If we are talking about moving megabytes of data to perform a 50ms operation, there is no benefit to offloading it to the background.

Perhaps we can think of it like this:

Total Time = Serialization Cost
  + Transit
  + Background Processing Time
  + Deserialization Cost

Looking at this, if the “background processing time” is the most dominant task in your operation, then isolation is the clear winner. But if serialization, plus deserialization, plus transit exceeds that cost, then there’s no need to isolate things.

And if you can’t figure out if the task is CPU-heavy or data-heavy, it certainly doesn’t hurt to measure it, for example, using performance.mark() and performance.measure() around postMessage calls to profile the transfer cost.

Aurélie RENARD-VIGNELLE, multi-DYS !

Par : Ideance
17 juillet 2026 à 09:13

Aurélie RENARD-VIGNELLES a 35 ans.

Diagnostiquée de 7 troubles DYS à l’âge de 10 ans, puis d’un TDAH à 30 ans,
elle a fait de son handicap le cœur de son métier : elle est aujourd’hui conférencière et
consultante spécialisée dans l’adaptation des contenus aux personnes DYS.

À l’occasion d’un atelier de sensibilisation qu’elle a animé,
elle a accepté de raconter son parcours.

Multi DYS, un fonctionnement différent

Je m’appelle Aurélie RENARD-VIGNELLES.

Je suis micro-entrepreneure, conférencière,
et comme plus de 7 millions de personnes en France, je suis DYS.

Transcription de la vidéo

Je m’appelle Aurélie RENARD-VIGNELLES, je suis micro-entrepreneuse et comme plus de 7 millions de personnes en France, je suis atteinte de troubles DYS.

Vous connaissez tous la dyslexie dont de grands génies comme Léonard de Vinci ou Einstein étaient atteints. Eh bien comme eux, je suis dyslexique, mais pas que, sinon ça serait trop facile.

Les troubles DYS se sont des handicaps cognitifs invisibles qui occasionnent un dysfonctionnement d’une ou plusieurs parties du cerveau.

Pour ma part j’ai les 7 troubles : la dyslexie, la dysorthographie, la dysgraphie, dyscaculie, la dysphasie, la dyspraxie et les troubles dysexécutifs. Comme beaucoup de personnes DYS, j’ai vécu les difficultés scolaires, la discrimination, le harcèlement, l’incompréhension, la solitude.

Mais grâce au soutien de nombreuses personnes telles que : ma famille, mes amis, certains spécialistes, certains enseignants et professeurs bienveillants, je me suis acceptée telle que je suis : avec mes difficultés, certes, mais surtout avec mes forces.

Grâce à mon handicap, j’ai appris à faire de chacun de mes échecs, une opportunité de m’améliorer. Ainsi suite à la rupture de mon contrat de stage de fin d’études de 2ème année de master en informatique, j’étais plus que motivée. Et j’avais envie de montrer que j’étais capable de travailler, malgré mon handicap encore trop peu connu des recruteurs.

Je me souviendrais toujours de cette phrase qu’une RH m’avait dit au téléphone : « Madame RENARD, vous avez les compétences mais vous êtes trop lente c’est pour ça qu’on ne vous prend pas !!! » C’est ainsi que quelques années après ma première conférence sur les troubles DYS en entreprise, j’ai eu l’éclair de génie. J’ai cette force, cette imagination, cette créativité, cette empathie, cette sensibilité, tous ces supers-pouvoirs qui me viennent de mon handicap à force d’adaptation et de compensation…

Ce jour-là, j’ai donc décidé de créer mon entreprise, dans l’espoir de sensibiliser le plus grand nombre aux troubles DYS. Et de montrer qu’en étant DYS, on peut changer le monde, en innovant grâce aux contraintes que nous imposent nos difficultés. Einstein aurait dit : « Tout le monde est un génie ! Mais si vous jugez un poisson à sa capacité à grimper aux arbres, il pensera toute sa vie qu’il est stupide ! »

Alors valorisons les forces de chaque être vivant sur cette Terre et mettons de côté leurs difficultés ! Ma force ? Mon handicap !

Vous connaissez sans doute la dyslexie :
de grands noms comme Léonard de Vinci ou Einstein en étaient atteints.
Eh bien moi, je suis dyslexique, mais pas seulement. Sinon, ce serait trop facile.

J’ai 7 troubles DYS :

  • La dyslexie.
  • La dysorthographie.
  • La dysgraphie.
  • La dyscalculie.
  • La dysphasie.
  • La dyspraxie.
  • Et les troubles dysexécutifs.

J’ai été diagnostiquée à l’âge de 10 ans. 20 ans plus tard, à 30 ans, j’ai reçu un second diagnostic :
un TDAH, un Trouble du Déficit de l’Attention avec Hyperactivité.

Les troubles DYS sont des handicaps cognitifs « invisibles ».

Ils viennent d’un dysfonctionnement d’une ou plusieurs zones du cerveau,
et ils sont durables : ce ne sont ni une déficience intellectuelle ni une maladie qui se guérit.

On ne les voit pas, mais ils sont là, tous les jours, à l’école, au travail, dans la vie quotidienne.

Pour vous donner une idée concrète de ce que ça veut dire,
vivre avec ces 7 troubles DYS :

  • La dyslexie
    engendre des difficultés en lecture.
  • La dysorthographie,
    des difficultés en orthographe et en conjugaison.
  • La dysgraphie,
    des difficultés à dessiner les lettres.
  • La dyscalculie
    touche les mathématiques, l’arithmétique, la logique.
  • La dysphasie
    est un trouble du langage oral, on peut avoir des difficultés
    à comprendre ce qu’on nous dit et / ou à s’exprimer à l’oral.
  • La dyspraxie
    engendre des difficultés de coordination des gestes et d’orientation dans l’espace.
  • Les troubles dysexécutifs,
    moins connus, touchent l’organisation, la planification et la priorisation des tâches.
    Ils sont souvent associés au TDAH.

On me demande souvent si le TDAH et les troubles DYS, c’est la même chose. Ma réponse honnête :

Les troubles DYS et le TDAH sont 2 choses différentes, néanmoins ils font partis tous les 2 des troubles du neurodéveloppement.

On peut être DYS et TDAH et être TDAH sans être DYS. Mais les 2 touchent les fonctions exécutives.

« Vous avez les compétences, mais vous êtes trop lente »

Mon handicap, je l’ai vécu de plein fouet dans le monde du travail.

Mon contrat de stage de fin d’études, en 2e année de master en informatique, a été rompu :
j’étais soi-disant « passive » en réunion, alors que j’avais bien expliqué mes troubles à l’employeur
et demandé des aménagements.

On m’avait pourtant dit oui, pas de problème.
Certaines entreprises, malheureusement, ne jouent pas franc jeu.

Malgré cet échec, j’étais plus motivée que jamais : je voulais montrer que j’étais capable de travailler,
malgré un handicap encore trop peu connu des recruteurs.

Je me souviendrai toujours de cette phrase qu’une chargée de recrutement m’a dite au téléphone :

Madame Renard, vous avez les compétences, mais vous êtes trop lente. C’est pour ça qu’on ne vous prend pas.

Cette lenteur, ce n’est pas un manque de volonté.
C’est que, pour une personne DYS, c’est un peu comme si on réapprenait à faire les choses à chaque fois, ou presque. Avec de la rééducation, ça peut s’améliorer.

Mais ça reste une donnée de base à comprendre, pas un défaut à corriger.

Transformer chaque échec en opportunité

Grâce à mon handicap, j’ai appris à faire de chacun de mes échecs une opportunité de m’améliorer.

Quelques années après ma première conférence sur les troubles DYS en entreprise,
j’ai eu ce qu’on pourrait appeler un déclic.

J’ai cette force, cette imagination, cette créativité, cette empathie, cette sensibilité,
et tous ces éléments me viennent justement de mon handicap, de ma capacité d’adaptation et de compensation.

Ce jour-là, j’ai décidé de créer mon entreprise, avec l’espoir de sensibiliser le plus grand nombre,
et de montrer qu’en étant « DYS », on peut changer le monde en innovant
grâce aux contraintes que nous imposent nos difficultés.

J’aime beaucoup cette phrase, qu’on attribue à Albert Einstein
(lui-même soi-disant dyscalculique, dyslexique, TDAH et haut potentiel) :

Tout le monde est un génie.
Mais si vous jugez un poisson à sa capacité à grimper aux arbres,
il passera sa vie à croire qu’il est stupide.

Valorisons les forces de chaque personne, et mettons de côté le jugement sur ses difficultés.

Se mettre à la place d’une personne DYS, le temps d’un atelier

J’ai créé mon entreprise 6foisdys, en 2018.

Dans mes ateliers de sensibilisation, je ne me contente pas d’expliquer : je fais vivre.

Ce que je veux, avec ces mises en situation, ce n’est pas faire pitié.
C’est faire comprendre, de l’intérieur, ce que vivent des millions de personnes,
un Français sur 10, environ 7 millions de personnes en France.

J’ai aussi écrit un livre, pensé pour être accessible au plus grand nombre :
« Moi, neuro atypique, le secret de ma résilience », primé aux « Talentéo Awards 2025 » dans la catégorie rédactionnelle.

Il est disponible en différents formats : ebook, audio et papier.

Mes outils du quotidien

On me demande souvent quels outils j’utilise pour naviguer sur le web ou lire un document.

Le mode lecture, d’abord : celui de Firefox est nettement plus performant que celui d’Edge
pour rendre un contenu accessible, même quand la page d’origine ne l’est pas.

Capture d'écran d'un affichage classique pour la page - troubles dys - de Wikipédia, en comparaison à un affichage plus sobre avec le mode lecture activé.

J’utilise aussi Google Lens pour photographier un numéro ou un texte plutôt que de m’épuiser à le déchiffrer.

Et pour certaines choses que je ne comprends pas du premier coup,
je n’hésite pas à demander à ChatGPT, à Gemini ou, tout simplement, à des humains autour de moi.

Ce que je voudrais que vous reteniez

Être DYS, c’est aussi avoir des forces et des qualités :

  • Une vision différente du monde.
  • De l’imagination (beaucoup de réalisateurs, comme Tim Burton ou Steven Spielberg, sont dyslexiques).
  • De la créativité.
  • De la persévérance (on représente souvent la persévérance par un lion, parce qu’il lui faut 5 à 7 tentatives avant d’attraper sa proie ; il n’abandonne pas à la première difficulté).
  • Du courage.
  • Et de l’empathie.

Quelles solutions pour les personnes DYS ?

  • De la rééducation (orthophoniste, psychomotricien, etc.).
  • Du soutien psychologique (parce que ces troubles peuvent fragiliser la confiance en soi).
  • Et des aménagements, à l’école, au travail, au quotidien.
    En France, la reconnaissance de la qualité de travailleur handicapé (RQTH) peut être demandée auprès de la maison départementale de l’autonomie (MDA), même si les délais sont longs, parfois 9 mois ou plus selon les régions.
  • Mais surtout : valoriser les forces de la personne, être à l’écoute, être patient (parce qu’être dys, c’est aussi parfois être plus lent) et être bienveillant.
    Ça va de soi, mais je préfère toujours le redire.

Je terminerai par cette phrase qui résume tout ce que j’essaie de transmettre : transformons les diversités en opportunités d’innover.

C’est la faute aux écolos

17 juillet 2026 à 08:41
« Ils attendent quoi, les élus et les journalistes, pour écouter enfin les scientifiques sur le changement climatique ? Une énorme canicule ?» L’été 2026 donne une terrible réponse à ces interrogations que nous osions à peine exprimer. L’intégrité devrait pousser au mea culpa ceux qui ont depuis des années contribué à nier l’urgence d’agir face au […]
❌