<!-- create and run web-worker with the inline code. --><web-workerid="worker" last-message="{{reply}}"><scripttype="text/js-worker">onmessage=function(e){postMessage(e.data.a+e.data.b);};</script></web-worker><!-- data-binded div to show msg from worker --><div>1 + 2 = <b>[[reply]]</b></div><!-- button to run function --><buttononclick="javascript:document.querySelector('#worker').postMessage({a: 1, b: 2});">Calculate 1+2</button>bower install --save PolymerVis/web-worker
More examples and documentation can be found at web-workerwebcomponents page.
PolymerVis is a personal project and is NOT in any way affliated with Polymer or Google.
web-worker is a Polymer 2.0 element to provide an easy way to data-bind with a web worker-based task. Compute-intensive tasks are usually done on a web worker to prevent blocking of the UI thread.
Creating a web worker from a URL.
<web-workerurl="some_script.js"></web-worker>Creating a web worker through script attribute.
<web-workerscript="postMessage('hello!');"></web-worker>Creating a web worker from inline code.
<web-worker><scripttype="text/js-worker">postMessage('hello!');</script></web-worker>Data-bind to the last message/reply from the worker with the last-message attribute.
<web-workerlast-message="{{reply}}"><scripttype="text/js-worker">postMessage('hello!');</script></web-worker>Or listen to the message event.
<web-workeron-message="onReply"><scripttype="text/js-worker">postMessage('hello!');</script></web-worker>You can post a message to the worker with postMessage function or through one of the 3 message attributes (text-to-worker, object-to-worker, or array-to-worker).
postMessage function
varele=document.createElement('web-worker');// create web-worker elementele.url='some_script.js';// set url to worker scriptele.postMessage('hello!')// return a Promise to the next message from worker.then(reply=>console.log(reply));Data-binding to text-to-worker, object-to-worker, or array-to-worker
<web-workerurl="some_script.js"
text-to-worker="hello"
last-message="{{reply}}"></web-worker>You can wrap a function and execute it in a once-off web worker with executeFnOnce. This function must be stateless and has no external dependencies, as the function and arguments are serialized and executed in the worker context.
document.createElement('web-worker')// create web-worker element.executeFnOnce((a,b)=>a+b,a,b)// serialized function and run in worker.then(sum=>alert(a+' + '+b+' = '+sum));// return a Promise to the outputYou can execute once-off web workers with executeUrlOnce.
document.createElement('web-worker').executeUrlOnce('echo.js','hello').then(msg=>console.log('msg'));npm test