Created by: iansu
Use worker-loader
to turn any file that ends with .worker.js
into a WebWorker.
Closes #3660
Here is the sample WebWorker code I used to test this:
// hello.worker.js
let helloInterval;
const sayHello = () => {
self.postMessage({ message: 'Hello' });
};
self.addEventListener('message', event => {
if (event.data.run === true) {
self.postMessage({ status: 'Worker started' });
helloInterval = setInterval(sayHello, 1000);
}
if (event.data.run === false) {
self.postMessage({ status: 'Worker stopped' });
clearInterval(helloInterval);
}
});
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import HelloWorker from './hello.worker.js';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
const helloWorker = new HelloWorker();
let messageCount = 0;
helloWorker.postMessage({ run: true });
helloWorker.onmessage = event => {
if (event.data.status) {
console.log('STATUS', event.data.status);
}
if (event.data.message) {
messageCount += 1;
console.log('MESSAGE', event.data.message);
if (messageCount >= 5) {
helloWorker.postMessage({ run: false });
}
}
}