HTML5 Web Workers
To carry complex and long operations without blocking the browser.
Web Workers API
Square Series of Number 2 using Web Workers:
2.But modern browsers have separated the processing of interface code from the web-page code.Thus making the browser quicker, responsive and more flexible while handling expensive and malicious script.
3. With HTML5 Webworkers API you can offload expensive process to another threads runnung in the background without interrupting the processing of UI interactions or other events within the main script.
Browser Support for Web-Workers API
1.The Web Workers API is supported on latest versions of all major browsers.
Internet Explorer, Apple Safari, Mozilla Firefox, Opera , Google Chrome.
2.Before you use Web Workers on your web document, you need to make sure its supported on the browser. If not you can provide fallback or alternate text, prompting users to update browser
Example: Check Browser Support.Run the CODE»
Creating Web Workers.
1.Creating new Web Workers takes up initial memory space but allows you to carry complex operations in background thus making webpages responsive to user inputs at all time .
Example:Creating a Web Worker.
Communication with Web Workers.
1.A Web Worker is started by calling the method postMessage().
2.Also, communication between the Web Worker and the main page is done using the method postMessage() .
Example: Communication with Web Workers.Note-Communication and data transfer between the calling script and the worker and vice-versa takes place via the postMessage() function.
Adding a event handler within the Code.
1.You can add an onmessage event handler which responds to requests by calling script postMessage().
2.This method provides the webWorker with the data needed for calculation and starts the computation process.
Example: Adding an event handler within the Code
Terminating the Web Worker .
1.Web Workers can be terminated by the page that created them using Web Worker's method terminate().
2.Terminating a Web Worker reclaims the resources assigned to it.But, you cannot restart a Web Worker, instead you have to create a new Web Worker with the same URL.
3. A Web Worker can terminate itself using the method nsIWorkerScope.close()
Example: Terminating a Web Worker
Final Web Worker Code.
1.The Code below is an entire sum up of all the concepts we learnt in above section.