-
Hello, Here's my setup:
Then I put a sample worker file under self.addEventListener('message', (event) => {
console.log('Worker received:', event.data)
self.postMessage('pong');
}); I tried to just create a worker in the function Home() {
const worker = new Worker("/sampleWorker.js");
// ... rest of code
} I would think this will work, but I got the error:
Can someone kindly let me know what I missed? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Try IPC-communication. It is more secure and it will allow you to offload tasks. Offloading tasks to the main process or another renderer process can help in balancing the workload and ensuring the UI remains responsive. For example, if a renderer process is busy with animations or user interactions, a CPU-intensive task can be sent to the main process to avoid jank or freezing. |
Beta Was this translation helpful? Give feedback.
-
@bm777 Thanks for the suggestion. For those who still wants to use the Web Worker api from the client side and run into this issue. const workerRef = React.useRef<Worker>(null);
React.useEffect(() => {
workerRef.current = new Worker("sampleWorker.js");
workerRef.current.onmessage = (e) => { };
return () => {
workerRef.current.terminate(); // Clean up on component unmount
}}, []); |
Beta Was this translation helpful? Give feedback.
-
@zhuoqyin happy that you found a solution and thanks for sharing it :) |
Beta Was this translation helpful? Give feedback.
@bm777 Thanks for the suggestion.
For those who still wants to use the Web Worker api from the client side and run into this issue.
I figured that the problem I had is that Next.js tries to pre-render pages on the server side.
You should create the worker in a react effect to guarantee the logic happens in the client side.