Unlike an asynchronous Ajax call, HTML5 Web workers provide an opportunity to run a Multi-threaded JavaScript code in modern browsers that support them. Each worker spawns an isolated thread with dedicated JavaScript Event Loop, Stack and Heap memory. For example a regular Ajax Call to MVC Web API service call goes through the following asynchronous call cycle.
The JavaScript Event Loop in this case could be interrupted by events that are being executed on the UI; for instance, a "window.alert", could possibly stop all scripts on the page from executing until a user responds.
Replacing the Ajax Call with HTML5 web worker provides a great way to run long running scripts in separate threads so that asynchronous code execution is not interrupted by UI events. Here is the a JavaScript worker implementation of the same MVC Web API call using a JavaScript web worker.
Despite the advantages of using a web worker, implementing one requires working with some constraints. The worker runs in a separate thread and isolated scope, it doesn't have access to global JS objects including "window" and DOM elements, asynchronous calls would also have to be called via plain "XMLHttpRequest" rather than libraries such as jQuery.ajax.
The following simple utility replaces a regular Ajax call with web worker to make use of Multi-threaded JS implementation in HTML5.
WebWorkerAjax.js
Using the Worker Script
I found the method useful in processing long running scripts such a data from live HTML5 camera and audio streams. The script takes a URL of an MVC web API call with parameters and returns results from the Web API.
To use the script.
1- Save the JS script (above) as "WebWorkerAjax.js"
2- Start the web worker as follows
You can download the "WebWorkerAjax.js" code along with a sample MVC application on GitHub.
Replacing the Ajax Call with HTML5 web worker provides a great way to run long running scripts in separate threads so that asynchronous code execution is not interrupted by UI events. Here is the a JavaScript worker implementation of the same MVC Web API call using a JavaScript web worker.
Despite the advantages of using a web worker, implementing one requires working with some constraints. The worker runs in a separate thread and isolated scope, it doesn't have access to global JS objects including "window" and DOM elements, asynchronous calls would also have to be called via plain "XMLHttpRequest" rather than libraries such as jQuery.ajax.
The following simple utility replaces a regular Ajax call with web worker to make use of Multi-threaded JS implementation in HTML5.
WebWorkerAjax.js
// WebWorkerAjax:: Utility function to process ajax requests with HTML5 Web Worker // Request params {URL:"", PostData: {}} e.g. {URL: '/Service/LongProcess', JSON.stringify({ input: "Test" })) // Adapted from http://stackoverflow.com/questions/2557247/easiest-way-to-retrieve-cross-browser-xmlhttprequest var WebWorkerAjax = { processRequest: function (request) { var req = this.createXMLHTTPObject(); var isPost = (request.PostData) ? true : false; // Use Post if postData is passed if (!req) return; var method = isPost ? "POST" : "GET"; req.open(method, request.URL, true); if (isPost) { req.setRequestHeader("Content-type", "application/json; charset=utf-8"); } //Send request if (req.readyState == 4) return; req.send(request.PostData); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status == 200) { WebWorkerAjax.finishRequest(req.response); } }; req.onerror = function (e) { console.log(e.error); }; }, finishRequest: function (data) { postMessage(data); }, createXMLHTTPObject: function () { var xmlhttp = false; for (var i = 0; i < this.XMLHttpFactories().length; i++) { try { xmlhttp = this.XMLHttpFactories()[i](); } catch (e) { continue; } break; } return xmlhttp; }, XMLHttpFactories: function () { return [ function () { return new XMLHttpRequest() }, function () { return new ActiveXObject("Msxml2.XMLHTTP") }, function () { return new ActiveXObject("Msxml3.XMLHTTP") }, function () { return new ActiveXObject("Microsoft.XMLHTTP") } ]; } }; this.onmessage = function (e) { WebWorkerAjax.processRequest(e.data); }
Using the Worker Script
I found the method useful in processing long running scripts such a data from live HTML5 camera and audio streams. The script takes a URL of an MVC web API call with parameters and returns results from the Web API.
To use the script.
1- Save the JS script (above) as "WebWorkerAjax.js"
2- Start the web worker as follows
var worker = new Worker("/scripts/WebWorkerAjax.js"); var postData = JSON.stringify({parameter object}); var request = { URL: "Absolute URL Path to Web API", PostData: postData }; worker.postMessage(request); worker.onmessage = function (e) { // Worker responded with data console.log(e.data); }
You can download the "WebWorkerAjax.js" code along with a sample MVC application on GitHub.
Comments