Even Faster Web Sites by Steve Souders

Even Faster Web Sites by Steve Souders

Author:Steve Souders
Format: mobi, epub, pdf
Tags: COMPUTERS / Web / Page Design
Publisher: O'Reilly Media
Published: 2009-06-03T23:00:00+00:00


XHR Streaming

The cleanest API for communication with the server is through an XMLHttpRequest, since it provides direct access to the response text and headers, and this is normally the transport mechanism used for polling and long polling. Several browsers provide support for streaming through XHR, including Firefox, Safari, Chrome, and Internet Explorer 8. Like the forever-frame technique, XHR streaming allows successive messages to be sent from the server without requiring a new HTTP request after each response.

While the lack of support for streaming in Internet Explorer versions 7 and earlier precludes complete reliance on a streaming-based protocol, we can certainly leverage streaming when it is available to improve performance. When available, XHR streaming is currently the best-performing Comet transport in the browser since it does not require the overhead of an iframe or script tags (as the forever-frame technique does), and can continuously utilize a single HTTP response (which long polling doesn’t do). While it is unfortunate that Internet Explorer does not support it, XHR streaming is still a valuable progressive enhancement. Users can upgrade browsers and instantly enjoy the benefit of improved performance.

XHR streaming is achieved with a standard XMLHttpRequest, but you can listen for onreadystatechange events with a readyState of 3 to access data that has been sent from the server (prior to the response being finished; that is, a readyState of 4), which allows you to handle data as it is received, without waiting for the connection to close:

function xhrStreaming(url, callback){

xhr = new XMLHttpRequest();

xhr.open('POST', url, true);

var lastSize;

xhr.onreadystatechange = function(){

var newTextReceived;

if(xhr.readyState > 2){

// get the newest text

newTextReceived =

xhr.responseText.substring(lastSize);

lastSize = xhr.responseText.length;

callback(newTextReceived);

}

if(xhr.readyState == 4){

// create a new request if the response is finished

xhrStreaming(url, callback);

}

}

xhr.send(null);

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.