Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does web workers does not give access to DOM object?

I have been using web-workers in javascript. It would have been an icing on the cake if window, document references were present in web workers context. I would like to know for what reason was it chosen to not make these references accessible in workers?

Also is there any work-around to use these references?

like image 810
Saba Hassan Avatar asked May 25 '15 08:05

Saba Hassan


1 Answers

Standard JavaScript and the DOM API have absolutely no exclusion mechanisms allowing several threads to safely access the same objects.

The solution that is most often chosen to allow multi-tasking in JavaScript is to isolate threads and only let them exchange through messages (or events). Giving access to the DOM to webworkers would break that isolation.

Note that this isn't totally specific to JavaScript: almost all GUI frameworks, whatever the language, restrict the modifications of the GUI to one dedicated thread. JavaScript is more restrictive as most often (always in the browser) you can't share objects at all.

The simple workaround is to let your main thread in the browser do the modifications you need to do, when the background thread gives it the instruction through messages. Or rather: do only the CPU extensive tasks in the webworker, letting the main thread obtain the input data, and update the DOM when the webworker sends the output data.

like image 155
Denys Séguret Avatar answered Oct 11 '22 01:10

Denys Séguret