I do not seem to be able to use jQuery in my webworker, I know there must be a way to do it with XMLHttpRequest
, but it seems like that might not be a good option when I read this answer.
-
i think ajax is now in all common webworker implimentations. it took a while to add it, fully with ajax2, but it's pretty solid now. – dandavis Dec 18 '13 at 16:47
-
ajax2? Care to explain? – qwertynl Dec 18 '13 at 16:47
-
XMLHttpRequest level 2: http://caniuse.com/xhr2 – dandavis Dec 18 '13 at 16:49
-
Can you show an example? – qwertynl Dec 18 '13 at 16:50
-
1no, jQuery doesn't work inside of web workers. you can use plain JS. you might be able to get Zepto or some of the node.js DOMs to work, but it would be a lot more work than simply using an iframe, which can run jQuery, jsonp calls, etc... – dandavis Dec 18 '13 at 16:53
3 Answers
Of course you can use AJAX inside of your webworker, you just have to remember that an AJAX call is asynchronous and you will have to use callbacks.
This is the ajax
function I use inside of my webworker to hit the server and do AJAX requests:
var ajax = function(url, data, callback, type) {
var data_array, data_string, idx, req, value;
if (data == null) {
data = {};
}
if (callback == null) {
callback = function() {};
}
if (type == null) {
//default to a GET request
type = 'GET';
}
data_array = [];
for (idx in data) {
value = data[idx];
data_array.push("" + idx + "=" + value);
}
data_string = data_array.join("&");
req = new XMLHttpRequest();
req.open(type, url, false);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onreadystatechange = function() {
if (req.readyState === 4 && req.status === 200) {
return callback(req.responseText);
}
};
req.send(data_string);
return req;
};
Then inside your worker you can do:
ajax(url, {'send': true, 'lemons': 'sour'}, function(data) {
//do something with the data like:
self.postMessage(data);
}, 'POST');
You might want to read this answer about some of the pitfalls that might happen if you have too many AJAX requests going through webworkers.
-
2To send JSON objects you'll need to do something along the lines of req.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); data_string = JSON.stringify(data); – Nathan Champion Feb 21 '19 at 22:10
If trying to call a service on another domain that uses JSONP, you can use the importScripts function. For example:
// Helper function to make the server requests
function MakeServerRequest()
{
importScripts("http://SomeServer.com?jsonp=HandleRequest");
}
// Callback function for the JSONP result
function HandleRequest(objJSON)
{
// Up to you what you do with the data received. In this case I pass
// it back to the UI layer so that an alert can be displayed to prove
// to me that the JSONP request worked.
postMessage("Data returned from the server...FirstName: " + objJSON.FirstName + " LastName: " + objJSON.LastName);
}
// Trigger the server request for the JSONP data
MakeServerRequest();
Found this great tip here: http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html

- 16,570
- 2
- 21
- 46
Just use JS function fetch() from Fetch API. You can also set up a lot of options like CORS bypassing and so on (so you can achieve the same behavior like with importScripts but in much cleaner way using Promises).
the code looks like this:
var _params = { "param1": value};
fetch("http://localhost/Service/example.asmx/Webmethod", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(_params )
}).then(function (response) {
return response.json();
}).then(function (result) {
console.log(result);
});
and the web.config of the webservice looks like this:
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>