Skip to content

Instantly share code, notes, and snippets.

@EtienneLem
Created June 10, 2013 19:40
Show Gist options
  • Save EtienneLem/5751589 to your computer and use it in GitHub Desktop.
Save EtienneLem/5751589 to your computer and use it in GitHub Desktop.
Ajax Web Worker
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()
})
// 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")
})
// 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
})
@EtienneLem
Copy link
Author

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!

worker.addEventListener('message', function(e) {
  // Right here
})

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:

var spawnWorker = function(page) {
  worker = new Worker('ajax_worker.js')
  worker.postMessage('/your/api/call?limit=5&page=' + page)
  worker.addEventListener('message', function(e) {
    var data, currentPage, nextPage, totalPages
    data = JSON.parse(e.data)

    // I’ll just assume you have a way to get `current_page`
    // and `total_pages` from your API provider
    currentPage = data.current_page
    totalPages = data.total_pages    
    nextPage = currentPage + 1

    if (nextPage <= totalPages) { spawnWorker(nextPage) }
    doActionWith(data)
  })
}

var doActionWith = function(data) {
  // Do whatever you want with the DOM, each `doActionWith`
  // call is in its own process
}

spawnWorker(1)

@freemaster
Copy link

How to use???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment