Search code examples
javascriptjqueryweb-worker

jQuery Rendering with Web Workers


I understand that Web Workers cannot access the main document DOM, but has anyone successfully tried to build a partial DOM in a Web Worker using jQuery, output the resulting HTML and then attach that to the document DOM?

Did it provide much of a performance improvement over rendering on the UI thread that is worth the extra pain of implementing this in a thread-safe way?

Would this be trying to use Web Workers for something they shouldn't be used for?


Solution

  • It depends a lot on what kind of HTML are you trying to generate. However there is one big problem you might have overseen. It's not just that you can't access main thread's DOM.

    You cannot create HTMLElement object instances in worker at all.

    So even if you go through the trouble of generating the HTML, you will then have to convert it to HTML string or JSON, parse it in the main thread and convert it to DOM object.

    The only case when this is worth it is when generating the data for HTML is CPU intensive. And in that case, you can just generate the data, send to main thread and display in HTML.

    This is also good approach to keep data processing and visual rendering separate.