Is it feasible to do an AJAX request from a Web Worker?

qwertynl picture qwertynl · Dec 18, 2013 · Viewed 19.8k times · Source

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.

Answer

qwertynl picture qwertynl · Dec 18, 2013

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.