Skip to content

Instantly share code, notes, and snippets.

@ffflabs
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save ffflabs/4d4c3cba4c47f8a44ba0 to your computer and use it in GitHub Desktop.

Select an option

Save ffflabs/4d4c3cba4c47f8a44ba0 to your computer and use it in GitHub Desktop.

jQuery vs WebWorker Request

The aim of this example is to show that, while jQuery will execute and resolve a bunch of request sequentially, delegating the task to webworkers will instead execute the request in parallel.

Be careful, this example will fire ~30 webworkers and may crash your browser.

The webworker is using pure javascript implementation of ajax request. jQuery kept throwing Cannot read property 'defaultView' of undefined error.

var citystates = [
['Montgomery', 'Alabama'],
['Juneau', 'Alaska'],
['Phoenix', 'Arizona'],
['Little Rock', 'Arkansas'],
['Sacramento', 'California'],
['Denver', 'Colorado'],
['Hartford', 'Connecticut'],
['Dover', 'Delaware'],
['Tallahassee', 'Florida'],
['Atlanta', 'Georgia'],
['Honolulu', 'Hawaii'],
['Boise', 'Idaho'],
['Springfield', 'Illinois'],
['Indianapolis', 'Indiana'],
['Des Moines', 'Iowa'],
['Topeka', 'Kansas'],
['Frankfort', 'Kentucky'],
['Baton Rouge', 'Louisiana'],
['Augusta', 'Maine'],
['Annapolis', 'Maryland'],
['Boston', 'Massachusetts'],
['Lansing', 'Michigan'],
['Saint Paul', 'Minnesota'],
['Jackson', 'Mississippi'],
['Jefferson City', 'Missouri'],
['Helena', 'Montana'],
['Lincoln', 'Nebraska'],
['Carson City', 'Nevada'],
['Concord', 'New Hampshire'],
['Trenton', 'New Jersey'],
['Santa Fe', 'New Mexico'],
['Albany', 'New York'],
['Raleigh', 'North Carolina'],
['Bismarck', 'North Dakota'],
['Columbus', 'Ohio']
];
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<style>
.container {
border:1px solid #CCC;
}
#jqresults, #wwresults {
font-size: 10px;
}
</style>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="citystates.js"></script>
<script>
/* global _:false, citystates:false*/
var goJquery= function(requestObj,callback) {
var theurl = ['http://echo.jsontest.com/city/',requestObj.city,'/state/',requestObj.state].join('');
jQuery.ajax({
url:theurl,
dataType:'json'
}).done(function(data) {
callback(data, requestObj.id);
});
};
var goWebWorker=function(requestObj,callback) {
var theurl = ['http://echo.jsontest.com/city/',requestObj.city,'/state/',requestObj.state].join('');
var worker = new Worker('webworker.js');
worker.addEventListener('message', function (e) {
var data=JSON.parse(e.data);
callback(data, requestObj.id);
}, false);
worker.postMessage(theurl); // Send data to our worker.
};
var formatResult=function(data) {
var formattedData=[];
_.each(data,function(value,key) {
formattedData.push('<b>'+key+'</b>: '+value);
});
return formattedData.join(', ').replace('%20',' ');
};
var getRequest=function(index,prefix,t0) {
var citystate=citystates[index];
var requestObj={
city:citystate[0],
state:citystate[1],
index:index,
timeini:(new Date().getTime() - t0),
id: prefix+index
};
requestObj.li = '<li id="'+requestObj.id+'">Request '+index+' fired_at: '+requestObj.timeini+' &nbsp;</li>';
return requestObj;
};
jQuery(document).ready(function() {
jQuery('#beginjrequests').click(function() {
var t0=_.now();
for(var index=0;index<citystates.length;index++) {
var requestObj = getRequest(index,'jqrequest',t0);
jQuery('#jqresults').append(requestObj.li);
goJquery(requestObj,function(data, id) {
data.finished_at=_.now()-t0;
jQuery('#'+id).append(formatResult(data));
});
}
});
jQuery('#beginwrequests').click(function() {
var t0=_.now();
for(var index=0;index<citystates.length;index++) {
var requestObj = getRequest(index,'wwrequest',t0);
jQuery('#wwresults').append(requestObj.li);
goWebWorker(requestObj,function(data, id) {
data.finished_at=_.now()-t0;
jQuery('#'+id).append(formatResult(data));
});
}
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-sm-6 col-xs-6" id="jquery_results">
<button class="btn btn-default" id="beginjrequests">Begin Jquery requests</button>
<ul id="jqresults">
</ul>
</div>
<div class="col-md-4 col-sm-6 col-xs-6" id="webworker_results">
<button class="btn btn-default" id="beginwrequests">Begin Webworker requests</button>
<ul id="wwresults">
</ul>
</div>
</div>
</div>
</body>
</html>
function load(url, callback) {
var xhr;
if (typeof XMLHttpRequest !== 'undefined') {
xhr = new XMLHttpRequest();
} else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
for (var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {}
} // end for
}
function ensureReadiness() {
if (xhr.readyState < 4) {
return;
}
if (xhr.status !== 200) {
return;
}
// all is well
if (xhr.readyState === 4) {
callback(xhr);
}
}
xhr.onreadystatechange = ensureReadiness;
xhr.open('GET', url, true);
xhr.send('');
}
self.addEventListener('message', function (e) {
load(e.data, function (xhr) {
var result = xhr.responseText;
self.postMessage(result);
});
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment