HTML and CSS Reference
In-Depth Information
13.2 Comet
Polling will definitely help move an application in the general direction of “live”
by making a more continuous data stream from the server to the client possible.
However, this simple model has two major drawbacks:
Polling too infrequently yields high latency.
Polling too frequently yields too much server load, which may be unnecessary
if few requests actually bring back data.
In systems requiring very low latency, such as instant messaging, polling to keep
a constant data flow could easily mean hammering servers frequently enough to
make the constant requests a scalability issue. When the traditional polling strategy
becomes a problem, we need to consider alternative options.
Comet, Ajax Push, and Reverse Ajax are all umbrella terms for various ways to
implement web applications such that the server is effectively able to push data to the
client at any given time. The straightforward polling mechanism we just built is possi-
bly the simplest way to do this—if it can be defined as a Comet implementation—but
as we have just seen, it yields high latency or poor scalability.
There are a multitude of ways to implement live data streams, and shortly we
will take a shot at one of them. Before we dive back into code, I want to quickly
discuss a few of the options.
13.2.1 Forever Frames
One technique that works without even requiring the XMLHttpRequest object
is so-called “forever frames.” A hidden iframe is used to request a resource from
the server. This request never finishes, and the server uses it to push script tags to
the page whenever new events occur. Because HTML documents are loaded and
parsed incrementally, new script blocks will be executed when the browser receives
them, even if the whole page hasn't loaded yet. Usually the script tag ends with a
call to a globally defined function that will receive data, possibly implemented as
JSON-P (“JSON with padding”).
The iframe solution has a few problems. The biggest one is lack of error hand-
ling. Because the connection is not controlled by code, there is little we can do if
something goes wrong. Another issue that can be worked around is browser loading
indicators. Because the frame never finishes loading, some browsers will (rightfully
so) indicate to the user that the page is still loading. This is usually not a desirable
Search WWH ::

Custom Search