Skip to content

Commit

Permalink
Test out fetch-with-keepalive on plausible.io (#5005)
Browse files Browse the repository at this point in the history
* Test out fetch-with-keepalive on plausible.io

Fetch with keepalive is a
[widely-supported](https://developer.mozilla.org/en-US/docs/Web/API/Request/keepalive)
which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.

We're hoping it will improve event capture rates for `pageleave` and
`pageview` events when the user closes the tab

To use it, we also need to start using `fetch` (with fallback to xhr).

For extra safety, we will only deploy this on `plausible.io` initially.
This will ensure that if there are issues we will be able to react
without affecting any other customers.

TODO after this PR:
- [ ] Companion docs PR
- [ ] Purge bunny cache
- [ ] Make fetch the default request method without data-property

* Mark some code conditional
  • Loading branch information
macobo authored Jan 23, 2025
1 parent 4f98259 commit 585c85b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/plausible_web/templates/layout/_tracking.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
data-api={PlausibleWeb.Dogfood.api_destination()}
data-domain={PlausibleWeb.Dogfood.domain(@conn)}
src={PlausibleWeb.Dogfood.script_url()}
data-allow-fetch
>
</script>
<script>
Expand Down
23 changes: 23 additions & 0 deletions tracker/src/plausible.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
{{/if}}
var endpoint = scriptEl.getAttribute('data-api') || defaultEndpoint(scriptEl)
var dataDomain = scriptEl.getAttribute('data-domain')
var allowFetch = scriptEl.hasAttribute('data-allow-fetch')

function onIgnoredEvent(eventName, reason, options) {
if (reason) console.warn('Ignoring Event: ' + reason);
Expand Down Expand Up @@ -221,6 +222,27 @@
}
{{/if}}

sendRequest(endpoint, payload, options)
}

function sendRequest(endpoint, payload, options) {
{{#if pageleave}}
if (allowFetch && window.fetch) {
fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
keepalive: true,
body: JSON.stringify(payload)
}).then(function(response) {
options && options.callback && options.callback({status: response.status})
})

return
}
{{/if}}

var request = new XMLHttpRequest();
request.open('POST', endpoint, true);
request.setRequestHeader('Content-Type', 'text/plain');
Expand All @@ -232,6 +254,7 @@
options && options.callback && options.callback({status: request.status})
}
}

}

var queue = (window.plausible && window.plausible.q) || []
Expand Down

0 comments on commit 585c85b

Please sign in to comment.