trailheadapps / lwc-recipes-oss

A collection of easy-to-digest code examples for Lightning Web Components on any platform.
https://lwc.dev
Creative Commons Zero v1.0 Universal
326 stars 253 forks source link

How to use web workers with LWC OSS #155

Closed sfdcale closed 3 years ago

sfdcale commented 3 years ago

I am creating a nodejs app using LWC OSS and it needs to process large amount of data and for that I would like to use web workers to create better user experience but I am not sure how to use it. Could you add an example for that?

github-actions[bot] commented 3 years ago

Welcome! 👋

Thank you for posting this issue. 🙇🏼‍♂️ We will come back to you latest within the next 48h (working days). Stay tuned!

adityanaag3 commented 3 years ago

Hey @sfdcale - One way is to create the worker file in the resources folder and use it in a component.

Here is how the code would look like for a worker that runs whenever a button is clicked in LWC. When the button is clicked, LWC passes some data to the worker, the worker waits for 5 seconds and returns the data to LWC, which is then shown as an alert.

File: resources/worker.js

addEventListener('message', (event) => {
    setTimeout(() => {
        postMessage('The worker has completed executing using the data : ' + event.data);
    }, 5000);
});

File: src/modules/my/app.js

import { LightningElement } from 'lwc';

export default class App extends LightningElement {

    myWorker;

    launchWorker(){
        if(!this.myWorker){
            this.myWorker = new Worker('./resources/worker.js');
        }
        this.myWorker.postMessage("Some random string from LWC");
        this.myWorker.onmessage = (event) => {
            alert(event.data);
        };
    }

    disconnectedCallback(){
        this.myWorker.terminate();
    }
}

File: src/modules/app/app.html (Code omitted for brevity)

...
<div>
    <a class="link" onclick={launchWorker}>Launch Web Worker</a>
</div>
...
sfdcale commented 3 years ago

@adityanaag3 I was expecting "it is not supported" kind of reply :) Thank you so much for providing the sample code. This helps me.