-
Notifications
You must be signed in to change notification settings - Fork 14
Description
It would be interesting to consider an option for the beacon API where you could request the payload to be compressed before being sent.
With the sendBeacon() API today, if you want to do some sort of compression on the data before sending it, you would use the Compression Stream API, which is an async-only API.
Here's an example of doing this at e.g. page load time:
async function compressBlob(data) {
const stream = new Response(data).body
.pipeThrough(new CompressionStream('deflate'));
return new Response(stream).arrayBuffer();
}
(async function() {
var data = JSON.stringify(performance.getEntries());
// this will send OK
var dataGz = await compressBlob(data);
navigator.sendBeacon('/beacon?load', dataGz);
}());
Unfortunately if you wanted to do this at pagehide/beforeunload/unload, you can't utilize the Compression Stream API since it is async. You would be waiting for the stream callback (await), but by then the page would be unloaded:
(async function() {
window.addEventListener("pagehide", async function() {
var data = JSON.stringify(performance.getEntries());
// this will send OK
navigator.sendBeacon('/beacon?before-await', data);
// this will not send due to await
var dataGz = await compressBlob(data);
navigator.sendBeacon('/beacon?after-await', dataGz);
});
}());
If we could ask the browser to compress the payload before sending, it could look something like this:
navigator.sendBeacon('/beacon?after-await', data, {
compress: "deflate"
});
And we could easily get it compressed from unload-style events (assuming the browser handles that async compression and beaconing later).