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 !

2
  • Try reading about Worker.postMessage(). Commented Jul 9, 2015 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. Commented Jul 9, 2015 at 21:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thank you for your answer and the links ! Well, I guess I will have to figure out another way then !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.