- In my previous post we have learn about dedicated worker and created a date time worker.
- In this demo, “We will learn to create inline worker”.
- A inline worker can be created using script element and type attribute with value text/worker.The following code shows the syntax of the inline worker script.
<script id="multiplyWorker" type="javascript/worker"> //Worker definition goes here </script>
- A worker object is created using new Worker(URL) initialization.It means the Worker() constructor takes a URL string.To achieve this we need to use window.URL.createObjectURL() method.This method takes a blob object.A blob object can be created by taking the worker code as text content and passing it to new Blob() constructor.
- The following code shows the content of inlineWorkerDemo.html.A inline worker named multiplyWorker is define using script element with type attribute value text/worker.A blob object is created using Blob() constructor and passing the text code content script element of multiplyWorker.Then a URL is created suing createObjectURL() method and the Blob object.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Inline Web Worker Demo</title> </head> <body> <h1 id="resultContainer"></h1> <input type="number" id="number1" value="8" placeholder="Enter first number"> <input type="number" id="number2" value="10" placeholder="Enter second number"> <button id="multiplyButton">Multiply</button> <script id="multiplyWorker" type="javascript/worker"> self.addEventListener("message",function(event){ var requestData = event.data, number1 = requestData.number1, number2 = requestData.number2, multiplyResult = number1 * number2; self.postMessage({result:multiplyResult}); }); </script> <script> var textContent = document.querySelector('#multiplyWorker').textContent, workerBlob = new Blob([textContent]), workerURL = window.URL.createObjectURL(workerBlob), multiplyWorker = new Worker(workerURL), resultContainer = document.getElementById("resultContainer"), multiplyButton = document.getElementById("multiplyButton"), number1 = document.getElementById("number1"), number2 = document.getElementById("number2"); multiplyButton.addEventListener("click", function () { multiplyWorker.postMessage({ number1:parseInt(number1.value,10), number2: parseInt(number2.value,10) }); }); multiplyWorker.addEventListener("message", function (workerEvent) { var responseData = workerEvent.data, result = responseData.result; resultContainer.innerText = "Result: " + result; }); </script> </body> </html>
- The output of the inlineWorkerDemo.html file is as follows.
- The demo code can be found from the following JSBIN link.