Skip to content

Instantly share code, notes, and snippets.

@noamr
Last active May 16, 2023 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamr/f5b4944ce667d87d26407f4d285ec707 to your computer and use it in GitHub Desktop.
Save noamr/f5b4944ce667d87d26407f4d285ec707 to your computer and use it in GitHub Desktop.
PendingBeacon on top of fetchLater
class UserlandPendingBeacon {
#abortController = null;
// Let's imagine it's a list of plain objects.
#pendingEntries = [];
// URL, headers, defer options etc
#requestInit;
constructor(requestInit) {
this.#requestInit = requestInit;
this.#pendingEntries = [];
}
// This will abort an ongoing fetch, and will schedule a new deferred fetch
send(entries) {
if (this.#abortController)
this.#abortController.abort();
this.#pendingEntries = [...this.#pendingEntries, ...entries];
this.#abortController = new AbortController();
fetchLater({signal: this.#abortController.signal, body: JSON.stringify(this.#pendingEntries), ...this.#requestInit})
.then(() => {
this.#abortController = null;
this.#pendingEntries = [];
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment