Created
June 10, 2013 19:40
-
-
Save EtienneLem/5751589 to your computer and use it in GitHub Desktop.
Ajax Web Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var handleRequest = function(data) { | |
postMessage(data) | |
} | |
addEventListener('message', function(e) { | |
var xhr = new XMLHttpRequest | |
xhr.open('GET', e.data) | |
xhr.onreadystatechange = function(e) { | |
if (xhr.readyState === 4 && xhr.status === 200) { | |
handleRequest(xhr.responseText) | |
} | |
} | |
xhr.send() | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Credit goes to @bdc, see http://sharedfil.es/web-workers-KSaG7cyXFe.html | |
var handleRequest = function(data) { | |
postMessage(data) | |
} | |
addEventListener('message', function(e) { | |
importScripts(e.data + "?callback=handleRequest") | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standard Ajax request | |
var worker = new Worker('ajax_worker.js') | |
worker.postMessage('/your/ajax_request') | |
worker.addEventListener('message', function(e) { | |
data = e.data | |
}) | |
// JSONP Ajax request | |
var worker = new Worker('ajax_worker_jsonp.js') | |
worker.postMessage('http://domain.com/your/ajax_request') | |
worker.addEventListener('message', function(e) { | |
data = e.data | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay, why would you wrap an ajax request in a worker?
It’s not about the request per se, which shouldn’t be any faster. It’s all about the callback!
Whatever you have to do in that callback will be in its own background process (\O/). It really helps with initial page load time (especially on mobile) if you have lots of DOM manipulations, etc.
Pretty neat and fast when dealing with APIs’ pagination too: