+ Start a Discussion
Suraj PSuraj P 

Are WebWorkers supported in Lightning Components? If not, is there a work around?

I was trying to use JS WebWorkers for a long running process in my component and got the message that the 'Worker' constructor is invalid. Is there a workaround to this?
NagendraNagendra (Salesforce Developers) 
Hi Suraj,

Web Workers do currently work in Lightning Components (and apps) but they represent a security attack vector that is possibly not going to be something we can overcome in the initial release of the upcoming Locker Service security model for Lightning Platform. We are discussing this inside of R&D actively but tomorrow is actually feature freeze for Summer'16 and we have not managed to find a solution yet. That does not mean we won't but I cannot guarantee we will before Summer'16 deploys.
With that in mind...

Here is a quick fully working example that uses a worker to multiply 2 numbers:

Static resource named webworker:
onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}
webWorkerDemo.app:
<aura:application>
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
</aura:application>
webWorkerDemo.app.controller.js:
({
    init : function(component, event, helper) {
        var worker = new Worker("/resource/webworker");
        worker.onmessage = function(e) {
            alert('Message received from worker: ' + e.data);
        };

        worker.postMessage([2, 3]);
    }
})
ltng: require does not factor into web workers - its sole purpose is to load scripts and CSS into the main page and web workers load their javascript contents directly. A number of your attempted script refs are nonsensical from static resource perspective - e.g heavycalculations.js alone is not a static resource reference at all, and the /resource/*.js also do not make sense since those are not valid developer names. What is the structure of heavy calculations? Is it a single javascript file or a js file in a zip archive?

Hope this helps.

Kindly mark this as solved if my reply was helpful so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards,
Nagendra.