A Gatsby plugin to integrate web workers into your GatsbyJS app via workerize-loader.
With Yarn:
yarn add gatsby-plugin-workerize-loader -D
Or with npm:
npm install --save-dev gatsby-plugin-workerize-loader
Add plugin to gatsby-config.js
plugins: ['gatsby-plugin-workerize-loader']
Create a worker file with suffix .worker.js
e.g. search.worker.js
.
// search.worker.js
export async function search(searchInput) {
// expensive search procedure...
return searchResults
}
Import and instantiate the web worker in your source file. One caveat is web worker only works in browser environment.
// searchWorker.js
import SearchWorker from 'path/to/search.worker.js'
const searchWorker = typeof window === 'object' && new SearchWorker()
export default searchWorker
Use it in your component
// SearchComponent.js
import searchWorker from "path/to/seachWorker.js";
function SearchComponent() {
useEffect(() => {
searchWorker.search(searchInput).then(
searchResults => // do something with search results
);
}, [searchInput]);
}
Worker code is only downloaded and parsed when you first instantiate Worker i.e. new Worker()
. Automatic code-splitting 🔥🔥🔥.
With useRef within a component.
// SearchComponent.js
import SearchWorker from "path/to/search.worker.js";
function SearchComponent() {
const searchWorkerRef = useRef(null);
function getSearchWorker() {
if (!searchWorkerRef.current) {
searchWorkerRef.current = new SearchWorker();
}
return searchWorkerRef.current;
}
useEffect(() => {
getSearchWorker().search(searchInput).then(
searchResults => // do something with search results
);
}, [searchInput]);
}
// getSearchWorker.js
import SearchWorker from 'path/to/search.worker.js'
let searchWorker
export default function getSearchWorker() {
if (!searchWorker) {
searchWorker = new SearchWorker()
}
return searchWorker
}
// anywhere.js
import getSearchWorker from "path/to/getSearchWorker.js";
function someOperation (searchInput) {
getSearchWorker().search(searchInput).then(
searchResults => // do something with search results
);
// remaining steps
}
MIT