An Introduction to Web Workers JavaScript

 JavaScript Web Workers

JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. But JavaScript runtime is not run in single thread.

Let’s take big loop example if you run in the chrome and at the same time at Firefox you will encounter with a warning Unresponsive script.

Here what, web workers is a JavaScript API that allows you to run scripts in a separate thread from the main one. It can come in handy when you don’t want any hindrance in the execution of the main scripts.

Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

When a script is executing inside a Web Worker it cannot access the web page's window object (window.document), which means that Web Workers don't have direct access to the web page and the DOM API. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.


How Web Workers Work?

Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute.

 var worker = new Worker('bigLoop.js');

If your application has multiple supporting JavaScript files, you can import them importScripts() method which takes file name(s) as argument separated by comma

importScripts("helper.js", "anotherHelper.js");

communication between web worker and its parent page is done using the postMessage() method. Depending on your browser/version, postMessage() can accept either a string or JSON object as its single argument.

 

This makes use of postMessage() API to pass the communication back to main page –

 

Stopping Web Workers

Web Workers don't stop by themselves but the page that started them can stop them by calling terminate() method.

A terminated Web Worker will no longer respond to messages or perform any additional computations. You cannot restart a worker; instead, you can create a new worker using the same URL.

 worker.terminate(); 

Checking for Browser Support

is the syntax to detect a Web Worker feature support available in a browser. 


Comments

Popular posts from this blog

Oracle E-Business Suite Applications - R12 – PROCURE TO PAY CYCLE

Minification in JavaScript.