This website uses cookies and similar technologies to understand visitors' experiences. By continuing to use this website, you accept our use of cookies and similar technologies,Terms of Use, and Privacy Policy.

Jun 12 2012 - 07:47 PM
JavaScript Web Workers - Responsive UI
What is Web Worker ? < Wikipedia definition > Web Worker is a JavaScript script, executed from an HTML page, that runs in the background, independently of other, user-interface scripts that may also have been executed from the same HTML page. Why Web Workers ? In the current world of dynamic User Interface, web developers are making heavy use of client side scripts to give users best look and feel. According to IBM, for good user experience, any JavaScript code should not take more than 50ms to run. But the JavaScript code runs in sequential passion so nothing much can be done to comply with the standards, unless we divide the work in different threads. And with the evolution of multi cores, it has become possible to share the work among different threads to improve the performance of applications. In such case, Web Workers is just the kind of tool we need. Conceptualized with the thought of running the heavy computations in background over different threads, Web Workers has become an important functionality of HTML5. It is efficient in using multi cores of client side processor using sub workers as well as in providing responsive user interface. Where to use? < you must have figured out till now> Creating rich user interfaces, pre fetching or caching data for later use, code syntax highlighting or other text formatting, spell checker, background I/O or polling of web service, processing large array or JSON responses and in a lot of other scenarios where we need to do heavy computation. How to use? < its easy > 1. Put your javascript function in worker.js (can be done using inline javascript function too) 2. Create worker object - var worker = new Worker ("worker.js"); 3. Initiate worker by sending message to it -worker.postMessage("hello"); (message could be Json object too) 4. Receive message from worker - worker.onmessage = function (event) { var message = "Worker says " + event.data;}; 5. terminate the worker -worker.terminate(); 6. Handle error if any- worker.onerror = function(error) { do something}; To know more about Web Workers, check your browsers compatibility and see how it is performing, visit my page :-
Posted in: Knowledge SolutionsFYI|By: Avichal Badaya|2022 Reads