Search code examples
javascriptjquerydombrowserweb-worker

Why can't WebWorkers have access to the DOM?


We all know we can spin up some web workers, give them some mundane tasks to do and get a response at some point, at which stage we normally parse the data and render it somehow to the user right.

Well... Can anyone please provide a relatively in-depth explanation as to why Web Workers do not have access to the DOM? Given a well thought out OO design approach, I just don't get why they shouldn't?

EDITED:

I know this is not possible and it won't have a practical answer, but I feel I needed a more in depth explanation. Feel free to close the question if you feel it's irrelevant to the community.


Solution

  • The other answers are correct; JS was originally designed to be single-threaded as a simplification, and adding multi-threading at this point has to be done very carefully. I wanted to elaborate a little more on thread safety in Web Workers.

    When you send messages to workers using postMessage, one of three things happen,

    1. The browser serializes the message into a JSON string, and de-serializes on the other end (in the worker thread). This creates a copy of the object.
    2. The browser constructs a structured clone of the message, and passes it to the worker thread. This allows messaging using more complex data types than 1., but is essentially the same thing.
    3. The browser transfers ownership of the message (or parts of it). This applies only for certain data types. It is zero-copy, but once the main context transfers the message to the worker context, it becomes unavailable in the main context. This is, again, to avoid sharing memory.

    When it comes to DOM nodes,

    1. is obviously not an option, since DOM nodes contain circular references,
    2. could work, but in a read-only mode, since any changes made by the worker to the clone of the node will not be reflected in the UI, and
    3. is unfortunately not an option since the DOM is a tree, and transferring ownership of a node would imply transferring ownership of the entire tree. This poses a problem if the UI thread needs to consult the DOM to paint the screen and it doesn't have ownership.