JavaScript Web Workers Why do we need them Web workers handle computationally intensive tasks without blocking the other scripts the main program or the user interface Amazing They help you put and end to those nasty unresponsive script dialog that you ve all come across Some example uses ideas Prefetching and or caching data for later use Code syntax highlighting or other real time text formatting Spell checker Analyzing video or audio data Background I O or polling of webservices Processing large arrays or humongous JSON responses Image filtering in canvas Updating many rows of a local web database Inline same file worker thread example Note this txt content could be in doWork js and would be loaded using new Worker doWork js instead of using the Blob inline example shown here let txt self onmessage function e self postMessage msg from worker e data back Rest of worker script goes here let total 0 var interval setInterval function self postMessage worker tick total total 3000 if total 9000 clearInterval interval self postMessage Stopping the ticker 3000 window onload function var blob new Blob txt type text javascript Note window webkitURL createObjectURL in Chrome 10 var worker new Worker window URL createObjectURL blob worker onmessage function e console log Received e data worker postMessage hello Start the worker console log ready end onload Add onerror to worker thread to notify main program of any issues errors problems let txt self onmessage function e self postMessage msg from worker e data back Rest of worker script goes here askl aklds inject an error this will trigger an error message window onload function var blob new Blob txt type text javascript Note window webkitURL createObjectURL in Chrome 10 var worker new Worker window URL createObjectURL blob worker onmessage function e console log Received e data worker onerror function e console log Worker onerror e console log e lineno in e filename e message worker postMessage hello Start the worker console log ready end onload
window onload function var blob new Blob txt type text javascript Note window webkitURL createObjectURL in Chrome 10 var worker new Worker window URL createObjectURL blob worker onmessage function e console log Received e data worker postMessage hello Start the worker console log ready end onload Add onerror to worker thread to notify main program of any issues errors problems let txt self onmessage function e self postMessage msg from worker e data back Rest of worker script goes here askl aklds inject an error this will trigger an error message window onload function var blob new Blob txt type text javascript Note window webkitURL createObjectURL in Chrome 10 var worker new Worker window URL createObjectURL blob worker onmessage function e console log Received e data worker onerror function e console log Worker onerror e console log e lineno in e filename e message worker postMessage hello Start the worker console log ready end onload