- In my previous post we have learn about inline Web Worker scripts.
- In this demo, “We will learn to import external script inside worker using importScripts() function”.
- To demonstrate this we have created 3 files greatest-number-script.js,numberWorker.js and numberWorkerDemo.html file.
- In this demo the greatest-number-script.js file is going to be imported by numberWorker.js file.The greatest-number-script.js file has a method findGreatestNumber() function that is going to be used by the numberWorker.js file.
- The following code shows the content of greatest-number-script.js file. it contains a method name findGreatestNumber() among 2 input numbers.
var findGreatestNumber = function(number1,number2){ return number1>number2 ? number1 : number2; };
- The following code shows the content of numberWorker.js file .It imports the greatest-number-script.js file using importScripts() method.
self.addEventListener("message",function(event){ var numberWorker = self.importScripts('greatest-number-script.js'); var requestData = event.data, number1 = requestData.number1, number2 = requestData.number2, greatestNumber = findGreatestNumber(number1,number2); self.postMessage({result:greatestNumber}); });
- The following code shows the content of numberWorkerDemo.html file which used the numberWorker.js file to compare 2 numbers.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Time Web Worker Demo</title> </head> <body> <h1 id="resultContainer"></h1> <input type="number" id="number1" value="7" placeholder="Enter first number"> <input type="number" id="number2" value="9" placeholder="Enter second number"> <button id="greatButton">Find Greatest Number</button> <script> var numberWorker = new Worker("numberWorker.js"), resultContainer = document.getElementById("resultContainer"), greatButton = document.getElementById("greatButton"), number1 = document.getElementById("number1"), number2=document.getElementById("number2"); greatButton.addEventListener("click",function(){ numberWorker.postMessage({ number1:parseInt(number1.value,10), number2: parseInt(number2.value,10) }); }); numberWorker.addEventListener("message",function(workerEvent){ var responseData = workerEvent.data; resultContainer.innerText = "Greatest Number: "+responseData.result; }); </script> </body> </html>
- The output of the numberWorkerDemo.html file is as follows.
- The demo code can be found in the following PLUNKER link.