Created
April 8, 2012 22:05
-
-
Save icodejs/2340056 to your computer and use it in GitHub Desktop.
Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Beacons | |
// This technique is very similar to dynamic script tag insertion. JavaScript is used to create | |
// a new Image object, with the src set to the URL of a script on your server. This URL | |
// contains the data we want to send back in the GET format of key-value pairs. Note that | |
// no img element has to be created or inserted into the DOM. | |
var url = '/status_tracker.php'; | |
var params = [ | |
'step=2', | |
'time=1248027314' | |
]; | |
var beacon = new Image(); | |
beacon.src = url + '?' + params.join('&'); | |
beacon.onload = function() { | |
if (this.width == 1) { | |
// Success. | |
} | |
else if (this.width == 2) { | |
// Failure; create another beacon and try again. | |
} | |
}; | |
beacon.onerror = function() { | |
// Error; wait a bit, then create another beacon and try again. | |
}; | |
// Beacons are the fastest and most efficient way to send data back to the server. The server | |
// doesn’t have to send back any response body at all, so you don’t have to worry about | |
// downloading data to the client. The only downside is that it you are limited in the type | |
// of responses you can receive. If you need to pass large amounts of data back to the | |
// client, use XHR. If you only care about sending data to the server (with possibly a very | |
// simple response), use image beacons. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment