Recently, I decided to explore raw XmlHttpRequestObjects along with Comet Long Polling. While typically I would rely on GWT or another framework for this task, I wanted to expand my knowledge in the area.
Here's a snippet of the code I wrote:
function longPoll() {
var xhr = createXHR(); // Initializes an XmlHttpRequestObject
xhr.open('GET', 'LongPollServlet', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
...
}
if (xhr.status > 0) {
longPoll();
}
}
}
xhr.send(null);
}
...
<body onload="javascript:longPoll()">...
To prevent an unnecessary comet call when exiting the page, I enclosed the longPoll()
invocation within an if statement checking for status > 0
. This adjustment was necessary because I noticed that a final request is made when navigating away from the page or reloading it, causing issues especially in Firefox.
Question: Is verifying the status
as I did the most efficient way to address this issue, or are there better alternatives available?