# Web Workers

Run js files in background threads without blocking UI

Communicate with JS code that called it with messages

## Dedicated Worker

Only accessible by script that called it

main.js

```javascript
const myWorker = new Worker('worker.js');
//In React: 
//import jsxWorker from "../worker/jsx.js";
//const myWorker = new Worker(jsxWorker);

first.onchange = function() {
  myWorker.gs
  ([first.value,second.value]);
  console.log('Message posted to worker');
}

second.onchange = function() {
  myWorker.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

myWorker.onmessage = function(e) {
  result.textContent = e.data;
  console.log('Message received from worker');
}
```

worker.js

```javascript
//In React:
//export default () => {

importScripts('foo.js', 'bar.js'); //synchronous
importScripts('//example.com/hello.js');

if (window.Worker) {
  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);
  }
}

//}
```

### Using in React

Can use web pack

webpack.config.js

```javascript
    module: {
      strictExportPresence: true,
      rules: [
        //.....
            {
              test: /\.worker\.js$/,
              include: paths.appSrc,
              use: { loader: "worker-loader" }
            },
        //.......
```

component.js

```javascript
import JSXWorker from "./jsx.worker";

// console.log("Creating JSX Worker");
const worker = new JSXWorker();

worker.addEventListener("message", ({ data }) => {
```

## More

```javascript
myWorker.terminate();
```

Handle errors with `onerror` event handler

Workers can spawn more workers yay

## Shared Worker

Accessible by multiple scripts

Use port instead of messages to communicate

## Service Worker

Service Workers offer a lot more functionality for creating Progressive Web Apps which give a great experience for offline users or users with slow internet connections. The Service Worker can be used as a proxy for network events, allowing us to cache resources for offline use.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://openai.gitbook.io/code-cheatsheets/js/webjs/worker.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
