HTML5 Web WorkersThe Web Workers are the separate JavaScript code which runs in the background of the web page without affecting the user Interface. What is Web Worker?Everyone wants a website or application which work fast and can execute multiple operations simultaneously without affecting the performance of the page. However, sometimes we experience some delay response or degraded performance of page while executing some large operations. So this problem can be solved using the Web Workers. Web Workers are the multithreaded object which can execute multiple JavaScript in parallel without affecting the performance of the application or webpage. Following are some key features of the Web Workers:
Tips: Before working with HTML Web Workers you must have knowledge of JavaScript as the Web Worker depends on JavaScript.Types of Web Workers:In HTML5 Web Workers are of two types:
The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.
It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers. Note: In this section, we will use dedicated Web Workers.Web Workers Browser Support:Before learning the web Workers first, we need to check about the browser support. So following is the code which checks whether your browser is supporting or not. ExampleTest it NowCreation of Web worker file:To create a Web Worker file we need to create an external JavaScript file. Here we have created a web worker file for calculating the square of the number. And saved it with the name "worker.js". Below is the code for worker.js file. Creating the Web Worker Object:In above "worker.js" file, we have created the JS file for web Worker now it needs to call on an HTML file. To create the web worker object, you need to call the Worker() constructor. Following is the syntax to call and create the object of Web Worker: Sending messages between the Worker thread and main thread:All the communication of Worker thread depends on the postMessage() method and onmessage event handler. Terminating the Web Worker:If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination: Web Worker can be terminate in worker thread also by calling the close() method. ExampleTest it NowWorker.js file: Example Explanation:In the above example in HTML file we have used
Browser Support:
Next TopicHTML SSE |