Skip to content

Instantly share code, notes, and snippets.

@jnstq
Forked from ismasan/gist:229343
Created November 11, 2009 23:13
Show Gist options
  • Save jnstq/232422 to your computer and use it in GitHub Desktop.
Save jnstq/232422 to your computer and use it in GitHub Desktop.
/* Jquery plugin for quick Comet long polling connections
Nothing special about this (just a recursive Ajax call).
The key is having the server hold connections open until there's data to push back to the client.
This can be done with Nginx and the nginx_http_push_module (http://github.com/slact/nginx_http_push_module)
---------------------------------------------------------------------------*/
(function($){
var changed, etag;
var wait = 1000;
$.comet = function(url, success_callback, error_callback) {
$.ajax({
type: "GET",
dataType: "script",
url: url,
cache: true,
beforeSend: function(oXhr) {
oXhr.setRequestHeader('If-Modified-Since', changed);
oXhr.setRequestHeader('If-None-Match', etag);
},
success: function(data, a, b, c){
if(success_callback) success_callback(data);
},
error: function(a,b,c){
if(error_callback) error_callback(a,b,c);
},
complete: function (oXhr, textStatus) {
if(textStatus == "success"){
etag = oXhr.getResponseHeader('Etag');
changed = oXhr.getResponseHeader('Last-Modified');
$.comet(url, success_callback, error_callback);
} else {
wait = wait * 1.5;
setTimeout(function(){
$.comet(url, success_callback, error_callback);
}, wait);
}
}
});
};
})(jQuery);
/*
Usage
------------------------------------------------------*/
$.comet(function(data){
$('#content').prepend(data.someAttribute)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment