Avoid compiling pageleave variant and p.js (#5351)

* Avoid compiling pageleave variant

Instead, it's treated as a no-op. Tracker still serves it.

Compile wall time went down from 86s -> 46s.

* Vendor, no longer compile p.js

This was a legacy script variant which we keep for backwards
compatibility but little else.

* chore: Bump tracker_script_version to 6
This commit is contained in:
Karl-Aksel Puulmann 2025-04-29 09:42:48 +03:00 committed by GitHub
parent dda551e7f5
commit a3db3af806
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 11 additions and 129 deletions

2
.gitignore vendored
View File

@ -84,7 +84,7 @@ plausible-report.xml
/priv/geodb/*.mmdb.gz
# Auto-generated tracker files
/priv/tracker/js/*.js
/priv/tracker/js/plausible*.js
# Docker volumes
.clickhouse_db_vol*

View File

@ -10,6 +10,8 @@ All notable changes to this project will be documented in this file.
### Removed
- `pageleave` tracker script variant is no longer compiled but is still available from /js endpoint.
### Changed
- A session is now marked as a bounce if it has less than 2 pageviews and no interactive custom events.

View File

@ -61,12 +61,15 @@ defmodule PlausibleWeb.Tracker do
end
end
# Variants which do not factor into output
@ignore_variants ["js", "pageleave"]
defp sorted_script_variant(requested_filename) do
case String.split(requested_filename, ".") do
[base_filename | rest] when base_filename in @base_filenames ->
sorted_variants =
rest
|> List.delete("js")
|> Enum.reject(&(&1 in @ignore_variants))
|> Enum.sort()
Enum.join(["plausible"] ++ sorted_variants ++ ["js"], ".")

1
priv/tracker/js/p.js Normal file
View File

@ -0,0 +1 @@
!function(){var e=window.document.currentScript,r=new URL(e.src).origin;function o(e){console.warn("[Plausible] Ignoring event because "+e)}function a(){var e,i,n,t=JSON.parse((t="plausible_user",(t=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)")))?decodeURIComponent(t[1]):null));return t?{initial_referrer:t.initial_referrer&&decodeURIComponent(t.initial_referrer),initial_source:t.initial_source&&decodeURIComponent(t.initial_source)}:(t={initial_referrer:window.document.referrer||null,initial_source:getSourceFromQueryParam()},e="plausible_user",i=JSON.stringify({initial_referrer:t.initial_referrer&&encodeURIComponent(t.initial_referrer),initial_source:t.initial_source&&encodeURIComponent(t.initial_source)}),(n=new Date).setTime(n.getTime()+94608e6),n="; expires="+n.toUTCString(),document.cookie=e+"="+(i||"")+n+"; samesite=strict; path=/",t)}function i(e,i){var n,t;return/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(window.location.hostname)||"file:"===window.location.protocol?o("website is running locally"):"prerender"===window.document.visibilityState?o("document is prerendering"):((n=c.trackAcquisition?a():{}).n=e,n.u=window.location.href,n.d=c.domain,n.r=window.document.referrer||null,n.w=window.innerWidth,(t=new XMLHttpRequest).open("POST",r+"/api/event",!0),t.setRequestHeader("Content-Type","text/plain"),t.send(JSON.stringify(n)),void(t.onreadystatechange=function(){t.readyState==XMLHttpRequest.DONE&&i&&i.callback&&i.callback()}))}function n(e){i("pageview",e)}try{var c={domain:window.location.hostname},t={page:n,trigger:i,trackPushState:function(){var e,i=window.history;i.pushState&&(e=i.pushState,i.pushState=function(){e.apply(this,arguments),n()}),window.addEventListener("popstate",n)},configure:function(e,i){c[e]=i}},l=window.plausible.q||[];window.plausible=function(){var e=[].slice.call(arguments),i=e.shift();t[i].apply(this,e)};for(var s=0;s<l.length;s++)window.plausible.apply(this,l[s])}catch(e){(new Image).src=r+"/api/error?message="+encodeURIComponent(e.message)}}();

View File

@ -33,11 +33,10 @@ function compilefile(input, output, templateVars = {}) {
}
}
const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue", "pageleave"]
const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue"]
const variants = [...g.clone.powerSet(base_variants)].filter(a => a.length > 0).map(a => a.sort());
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
compilefile(relPath('src/p.js'), relPath('../priv/tracker/js/p.js'))
variants.map(variant => {
const options = variant.map(variant => variant.replace('-', '_')).reduce((acc, curr) => (acc[curr] = true, acc), {})

View File

@ -1,5 +1,5 @@
{
"tracker_script_version": 5,
"tracker_script_version": 6,
"scripts": {
"deploy": "node compile.js",
"test": "npm run deploy && npx playwright test",

View File

@ -1,123 +0,0 @@
// NOTE: This file is deprecated and only kept around so we don't break compatibility
// with some early customers. This script uses a cookie but this was an old version of Plausible.
// Current script can be found in the tracker/src/plausible.js file
(function(){
'use strict';
var scriptEl = window.document.currentScript;
var plausibleHost = new URL(scriptEl.src).origin
function setCookie(name,value) {
var date = new Date();
date.setTime(date.getTime() + (3*365*24*60*60*1000)); // 3 YEARS
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + (value || "") + expires + "; samesite=strict; path=/";
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : null;
}
function ignore(reason) {
console.warn('[Plausible] Ignoring event because ' + reason);
}
function getUserData() {
var userData = JSON.parse(getCookie('plausible_user'))
if (userData) {
return {
initial_referrer: userData.initial_referrer && decodeURIComponent(userData.initial_referrer),
initial_source: userData.initial_source && decodeURIComponent(userData.initial_source)
}
} else {
userData = {
initial_referrer: window.document.referrer || null,
initial_source: getSourceFromQueryParam(),
}
setCookie('plausible_user', JSON.stringify({
initial_referrer: userData.initial_referrer && encodeURIComponent(userData.initial_referrer),
initial_source: userData.initial_source && encodeURIComponent(userData.initial_source),
}))
return userData
}
}
function trigger(eventName, options) {
if (/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(window.location.hostname)) return ignore('website is running locally');
if (window.location.protocol === 'file:') return ignore('website is running locally');
if (window.document.visibilityState === 'prerender') return ignore('document is prerendering');
var payload = CONFIG['trackAcquisition'] ? getUserData() : {}
payload.n = eventName
payload.u = window.location.href
payload.d = CONFIG['domain']
payload.r = window.document.referrer || null
payload.w = window.innerWidth
var request = new XMLHttpRequest();
request.open('POST', plausibleHost + '/api/event', true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send(JSON.stringify(payload));
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
options && options.callback && options.callback()
}
}
}
function page(options) {
trigger('pageview', options)
}
function trackPushState() {
var his = window.history
if (his.pushState) {
var originalFn = his['pushState']
his.pushState = function() {
originalFn.apply(this, arguments)
page();
}
}
window.addEventListener('popstate', page)
}
function configure(key, val) {
CONFIG[key] = val
}
try {
var CONFIG = {
domain: window.location.hostname
}
var functions = {
page: page,
trigger: trigger,
trackPushState: trackPushState,
configure: configure
}
var queue = window.plausible.q || []
window.plausible = function() {
var args = [].slice.call(arguments);
var funcName = args.shift();
functions[funcName].apply(this, args);
};
for (var i = 0; i < queue.length; i++) {
window.plausible.apply(this, queue[i])
}
} catch (e) {
new Image().src = plausibleHost + '/api/error?message=' + encodeURIComponent(e.message);
}
})();

View File

@ -105,7 +105,7 @@ test.describe('engagement events', () => {
})
})
test('script.exclusions.hash.pageleave.js sends an event only from URLs where a pageview was sent', async ({ page }) => {
test('script.exclusions.hash.js sends an event only from URLs where a pageview was sent', async ({ page }) => {
const pageBaseURL = `${LOCAL_SERVER_ADDR}/engagement-hash-exclusions.html`
await expectPlausibleInAction(page, {