Search code examples
javascriptmultithreadingweb-workerdocumentfragment

Is manipulating documentFragment in webWorker legal in principle(multithreading)?


1.main_thread and work_thread don't share anything(share nothing in common)

2.constructing domFragment to some level of structure(base on data) all in main_thread is a little time consuming,and can be divide in to jobs for worker_thread.

however , i can find noway to pass in a DocumentFragment into work_thread

postMessage(fragment) // no way

postMessage({f:fragment}) // no way ,same reason above(serialization)

postMessage(fragment,[fragment]) // no way, type checking , must be a buffer type...

maybe this kind of optimizing is not worth the effort? any comments?


Solution

  • As the specification on W3C says, it is not possible to share any kind of a DOM API from your main thread with a worker thread.

    Excerpt from the spec:

    The DOM APIs (Node objects, Document objects, etc) are not available to workers [...]

    Since a DocumentFragment inherits at least from Node, it should be (nearly) impossible to send it to a webworker. I said nearly, because it might be possible to send it as a string (for example via innerHTML), but that means you would have to parse it in some way inside the worker thread or gather your information from that string. Personally, I don't think there is any smart way to do it.

    A possible solution might be to pass the raw data as JSON to your worker thread, construct a string there an pass that string back.