Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Run scripts in background threads and perform tasks without interfering with the user interface.
We all know that the JavaScript code executes in a single thread. It means that code will execute line by line and if a particular task takes a long time to complete everything else is held up until that task finishes. If we want to unload the main threat Web Workers what is all about.
âïž What you should know
Web Workers is supported almost in all browsers. For slightly more controlled error handling and backwards compatibility, it is a better way to do a check.
if (window.Worker) { ...}
Create only one instance, each call new Worker('worker.js') is going to load worker.js file. So, you may see something like that in Network.
React +Â Redux
With Redux update store is simple. So, we are going to have a place or a file where we create a Worker instance, export it and listen onmessage event where we dispatch an event when a data comes from the Worker.
In worker.js we may importScripts if we need to import some scripts to global worker scope. In Web Worker you may use XMLHttpRequest so in example below I import axios and use it for XHR calls. onmessage listener is called whenever new message bubbles through the worker. postMessage method sends a message to the workerâs inner scope.
Use Worker instance. Import already existing Worker and call postMessage method with data which you want to pass to the Worker worker.js
Conclusion
Web Workers is powerful API you should definitely use it. It is good for background sync, prefetching data, ray tracing. Using web workers can have a significant impact on the performance of your web application.
đ Useful links
- Using Web Workers
- The Worker interface
- Computing with JavaScript Web Workers
- Using Web Workers to Speed-Up Your JavaScript Applications
- Web Workers Spec
đ Thank you for reading. Suggestions, comments, thoughts are welcome đ
If you like this, clap, follow me on medium, twitter, github share with your friends đ
Web Workers in React + Redux application was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.