Reputation: 25
Since I've tried out webworkers for the first time I'm struggling to find a real use case for them. Communication with them isn't as easy as just passing objects or references, they don't have a window object so I can't use JQuery and the increased complexity of building an interface is not worth the load saved on the main thread. So all the options I'm left with are basically working through large arrays to gain a performance advantage.
Today I thought about opening a new window by window.open()
and use the newly created window object to do some task and pass the result back to the main window. I should even be able to access the DOM of the main window by accessing the window.opener
variable in the new window.
window.opener
variable and take the load of creating new DOM elements from the main thread?Upvotes: 0
Views: 619
Reputation: 53257
Is that really going to give me a performance advantage?
No, as long as you can access window.opener
or access objects from one tab to another, that means they share same instance of javascript interpreter, and javascript interpreter is single-threaded.
There is literally no (practical) way around this. You either have separate thread, or share same objects.
Are there any caveats about this idea besides more complicated debugging?
Main caveat: it does not work. Also caveat: separate window is probably not something suitable for production.
Can I access the DOM of the main window from the new window using the
window.opener
variable and take the load of creating new DOM elements from the main thread?
You can, but you should probably use correct document instance for calling document.createElement
.
So all the options I'm left with are basically working through large arrays to gain a performance advantage.
That's exactly what workers are for, unless you are processing large amount of raw data, they are probably not a solution to your problem.
If you have performance drops when creating DOM nodes, you're most likely doing something wrong. Remember that:
createDocumentFragment
exists for creating self contained element groups before appending them.innerHTML
causes DOM to rebalance tree in which you cahnged the HTMLnew Text
or document.createTextNode
can be used to fill in text without innerHTML
You should also profile your code using developper tools to see where is the performance bottleneck. WebWorker is for data processing (eg. resizing images before upload), not for DOM manipulation.
Final note: it's the end of 2019, "I can't use jQuery" shouldn't be a problem any more. We now have document.querySelector
and CSS animations, which were main uses of jQuery in the past.
Upvotes: 3