Long polling Comet
I've been working on a long-polling comet client from Amix at Plurk, who uses it to monitor messages on the server. While he simply provides it as a 'solution', not detailing the hurdles he overcame to get there, it's clear that there's some thought gone into it.
http://amix.dk/blog/post/19489#Comet-long-polling-for-all-browsers-using-ScriptCommunicator
The script requires you to set a variable in your jsonp response. The script checks whether that variable is true after the jsonp loads. If true, your json has loaded. If not, something has gone wrong.
So, if your jsonp looks like this:
callback({blah:"blah"});
You'll need to revise it to this:
callback({blah:"blah"});ScriptCommunicator.callback_called = true;
On the jQuery forums, John Resig said he isn't enamoured with this approach since it means adapting the jsonp response, and if you're using jsonp then you're probably not in control of the feed. It's a fair point, but you could simply add the callback_called variable into the callback function instead.
Plus, if you're running Comet long-polling, it's better to use a different domain for your comet feed, to prevent tying up threads in the browser. So jsonp is needed.
The "difficult" part of the process is knowing when to run the second script, that checks the callback_called value. Amix uses a variety of methods for different browsers to achieve this.
In Firefox (default case) -> create two script tags using document.createElement, and attach them to the body.
In IE -> use the onreadystatechange event to call onSuccess, and then detect errors there, based on the readyState (somewhat illogical).
In Safari/Chrome -> write two script tags out with document.writeln. Presumably, this is intended for use with an iframe, though that's not clear. OOTB, no webkit browsers receive data.
Having tried to hack the script to make the Safari browsers use the same method as Firefox, I've found that Safari's caching kicked in and failed to load new scripts from the server (though this could be my fault for not changing the script name each time).
Looking back at Plurk, the comet scripts are indeed in an iframe, so I think this script probably needs some more input before it's going to work for anyone else. Hopefully, Amix (or someone) will put together a demo page and make any necessary fixes to the script when making that work.
It's a very useful function/tool/script. Thanks Amix.
Thanks for reading! I guess you could now share this post on TikTok or something. That'd be cool.
Or if you had any comments, you could find me on Threads.
Published