From 52831cd117567299586808d5672ab42347543a42 Mon Sep 17 00:00:00 2001 From: Ayke Halder Date: Tue, 16 May 2023 15:57:28 +0200 Subject: [PATCH] PagePerformance: Delay log of page view/visit to include `onload` metric --- js/piwik.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/js/piwik.js b/js/piwik.js index bbdf165d858..f3584cdd967 100644 --- a/js/piwik.js +++ b/js/piwik.js @@ -4274,12 +4274,48 @@ if (typeof window.Matomo !== 'object') { // append already available performance metrics if they were not already tracked (or appended) if (configPerformanceTrackingEnabled && !performanceTracked) { + if (!performanceAvailable && supportsSendBeacon()) { + delayLogPageViewWithPerformanceMetrics(request, configTrackerPause, callback); + return; + } request = appendAvailablePerformanceMetrics(request); } sendRequest(request, configTrackerPause, callback); } + /* + * Delay log of page view / visit + * Wait until PerformanceMetrics are available or visitor leaves page. + */ + function delayLogPageViewWithPerformanceMetrics(request, configTrackerPause, callback) { + // - Ensure page view is only logged once. + // - Matomo context might change in the meantime: Store request in closure to ensure original context. + var logOnce = function() { + var store = { request: request, configTrackerPause: configTrackerPause, callback: callback}; + var hasRunOnce = false; + return function() { + if (!hasRunOnce) { + hasRunOnce = true; + store.request = appendAvailablePerformanceMetrics(store.request); + sendRequest(store.request, store.configTrackerPause, store.callback); + } + }; + }(); + + /* Performance metrics are available, once onload event has finished */ + trackCallbackOnLoad(function(){ + setTimeout(logOnce, 0); + }); + /* Visitor leaves page */ + addEventListener(windowAlias, 'visibilitychange', function () { + // if not visible + if (documentAlias.visibilityState === 'hidden') { + logOnce(); + } + }, false); + } + /* * Construct regular expression of classes */