Analytics and diagnostics code are very useful, but they always result in an extra time. To make things easier the Beacon API comes to our rescue!
As The Browser normally ignores asynchronous XMLHttpRequests made in an unload handler and a event on an unload or beforeunload handler is used to post such data to the server.
So, as a work around one would use:
Use synchronous XMLHttpRequest.
Delay the unload, using image element and setting its src attribute within the unload handler.
Create a no-op loop for several seconds within the unload handler.
All the above workarounds are indeed poor coding patterns.
The Beacon specification defines an interface that web developers can use to asynchronously transfer small HTTP data from the User Agent to a web server.
1 2 3 |
|
Parameters for the API :
a
URL
to which the data must be posted.Optional
data
which can ArrayBufferView, Blob, DOMString, or FormData data that is to be transmitted.
And it the retruns
true on success or else false.
So basically, something like:
1 2 3 4 5 6 7 8 |
|
Could be written as:
1 2 3 4 5 |
|
GIF FTW!:
Refferences:
What are people saying about this?
navigator.sendBeacon It's like UDP over TCP but for webpages. -- @FakeAlexRussell
A 'fire-and-forget' XMLHttpRequest replacement for faster page unloads (& next page loads) -- @richtibbett