A Simple Pattern For Adding a Web Worker in React
A web worker is a JavaScript script executed from an HTML page that runs in the background, independently of scripts that may also have been executed from the same HTML page according...
Introduction
A web worker is a JavaScript script executed from an HTML page that runs in the background, independently of scripts that may also have been executed from the same HTML page according to the World Wide Web Consortium. Web Workers require an origin so you cant open an HTML file you need a server to get started. Otherwise, you get the following error:Uncaught DOMException: Failed to construct 'Worker': Script at ... cannot be accessed from origin 'null'
https://github.com/mdn/simple-web-worker
Framework for adding simple web workers in react:
Dependencies: Workerize-Loader
Each folder in the folder structure has a responsibility:
- workers - contains logic that you want to offload to a web worker and return a result.
- utils/workerUtils.js - manages the web workers dispatching 1 worker or many workers and cleaning up web workers.
- components or pages - render to the browser, call the web worker update the browser with the result from the web worker when ready.
So what does this look like ?
Where is the magic?
Everything is simplified and managed by utils/workerUtils.js
.
Getting test suite to pass with the new changes for create react app
Source: https://github.com/developit/workerize-loader#with-webpack-and-jest
Add the following to your package.json
:
Create a file workerize-jest.js
in your project's root directory (where the package.json
is):
To see source code with a working project: https://github.com/MichaelDimmitt/simple-web-worker-react
Links:
Why you should use a Web Worker:
You should always use Web Workers - Web Advocate @Google
what the heck is the event loop - Popular Talk about the event loop by Philip Roberts
Workerize related links:
https://github.com/developit/workerize-loader
https://github.com/kentcdodds/react-performance
https://kentcdodds.com/workshops/react-performance
https://kevincunningham.co.uk/posts/kcd-react-performance
Mdn Links:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
The JBS Quick Launch Lab
Free Qualified Assessment
Quantify what it will take to implement your next big idea!
Our assessment session will deliver tangible timelines, costs, high-level requirements, and recommend architectures that will work best. Let JBS prove to you and your team why over 24 years of experience matters.