- In my previous post we have learn about error handling in web worker.
- In this demo, “We will learn about creating Shared Web Worker to calculate length of a string”.
- A Shared Worker can be used by multiple calling script.
- A shared worker can be created using new keyword and SharedWorker() constructor function.
- A Shared Worker can be started using start() method and can be stopped using close() method.
- A shared worker communicates using its port.
- This demo has a shared worker calculateLengthWorker.js and lengthWorkerDemo.html file.The calculateLengthWorker.js file contains the code for the worker which listens to connect event.
- The following code shows the content of calculateLengthWorker.js which can be connected.Once it is connected it retrieved the port from the connection event object and listen to incoming message using message event listener.Once the message is arrived it calculate the length and send the response by posting the message to port.
self.addEventListener("connect", function (event) { var port = event.ports[0]; port.addEventListener("message", function (event) { var requestData = event.data, inputString = requestData.string, stringLength = inputString.length; port.postMessage({result:stringLength}); }, false); port.start(); }, false);
- The lengthWorkerDemo.html file has the following code.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Shared Web Worker Demo</title> </head> <body> <h1 id="resultContainer"></h1> <input type="text" id="inputString" value="Hello" placeholder="Enter a string"> <button id="lengthButton">Get Length</button> <script> var lengthWorker = new SharedWorker("calculateLengthWorker.js"), resultContainer = document.getElementById("resultContainer"), lengthButton = document.getElementById("lengthButton"), inputString = document.getElementById("inputString"); lengthButton.addEventListener("click", function () { resultContainer.innerText = ""; lengthWorker.port.postMessage({ string:inputString.value }); }); //start the worker lengthWorker.port.start(); //Success Handler for the worker lengthWorker.port.addEventListener("message", function (workerEvent) { var responseData = workerEvent.data, result = responseData.result; resultContainer.innerText = "Result: " + result; }); </script> </body> </html>
- The output of the above code is as follows.
- The demo code can be found from the following PLUNKER link.