-
-
Save jnstq/232422 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* 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