1

I am currently on a big Javascript project with a lot of libraries. I would like to have some part of this project to run on separate thread. There is already something inJavascript doing that : the web workers.

Though, the web workers can't access the window object, and a lot of the libraries use it. Is there a way to automatically change the call to the window object (in the libraries used for the web workers), into a message sent to the parent thread ?

Then, the parent thread would perform the action that the worker want and send back the result to the worker.

Is it possible to do that ? And id yes, do you have any idea how ?

Thank you !

clementescolano
  • 485
  • 5
  • 15
  • Try reading about [Worker.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage). – Greg Burghardt Jul 09 '15 at 21:20
  • I am well aware of this function and it's sure I will use it to perform what I want to do. Though, what I am looking for is how to call this function automatically each time I want to access to the `window` object. – clementescolano Jul 09 '15 at 21:26

1 Answers1

1

I'm afraid there's no real solution to this. What you'd probably want is a special object in your worker, which, at every property access, passes the execution to the dispatching thread - which handles the request using the original window object.

To do this, you would need some sort of catch-all accessor method which would run whenever a property is referenced. Sadly, there's no such thing in Javascript, see this detailed discussion (especially T.J. Crowder's answer): Is it possible to implement dynamic getters/setters in JavaScript?

ECMAScript 6 introduces a new mechanism called Proxy (currently supported in FF and IE12 (go figure!)), which would enable you to do these dynamic property lookups, technically - but I feel there's a more fundamental problem with your idea: you're aiming to turn a local call into a message across the boundaries of single threaded environments.

Message passing from and to the worker threads must be asynchronous (as a javascript "thread" cannot be interrupted until it yields), which would mean that even if you do manage to set up a proxy like that, it'd be effectively turning a usually synchronous operation (ie. a property access) into an asynchronous one, which is a pretty big issue, especially if you're looking for a drop-in replacement in order to use some existing libraries.

Community
  • 1
  • 1
doldt
  • 4,466
  • 3
  • 21
  • 36