I’m looking at Javascript widget that has to work under the following constraints:
- The widget makes a request to a 3rd party server along with a callback URL
- The 3rd party server pings the callback URL after an arbitrary time, which should trigger a method to run within the widget
This is how the widget has been implemented:
- Server A has been setup. The widget appends a GUID parameter to a static URL that points to Server A.
- The widget sends this URL (with the GUID parameter) to the 3rd party server.
- Server X simply listens for requests from the 3rd party server and stores the GUID parameter from each request in a database.
- The widget polls Server A every X secs to see if the 3rd party server sent a callback with its GUID.
- If server returns an OK response, the widget runs the required method.
Seems like a fairly sketchy implementation. Isn’t there a simpler way to do this?
I would like to explore:
a) Whether it’s possible to avoid polling the server from the widget repeatedly? Can a keep-alive connection be setup? Can the widget subscribe to a server event? I looked at the Server-sent events API which allows push notifications to be sent by the server to the browser. But this isn’t compatible with IE yet.
b) Whether it’s possible to avoid setting up a backend altogether? WebSockets come to mind but I’m hazy on the details and the compatibility issues would make them undesirable.
Thanks.
Server messages and WebSockets alike are your two answers. Sadly, neither is ubiquitous, so you can’t use a vanilla implementation of either, and expect to have full support.
There are a few solutions out there (several paid, unfortunately), which offer WebSocket functionality on both ends, with fallbacks to Flash or long-polling.
Pusher is a library which immediately comes to mind.
There are several implementations of Pusher for whatever the backend may be, and the client will default to websockets, but will revert to Flash’s data-transfer format if possible.
They also have a REST API.
It all comes down to who you’re looking to support.
In the end, I don’t even know that you’d want to give IE6/7 users the full, real-time experience, even if you can…
…because the workarounds (ie: constant polling) for the worst-case are also the slowest-performing, which the slowest browsers would then be stuck using.