In deze handleiding wordt uitgelegd hoe u de totale tijd berekent die een gebruiker een pagina actief bekijkt. Traditionele statistieken zoals tijd op pagina bevatten vaak onterecht de tijd die op de pagina is doorgebracht op de achtergrond. Als u de VisibilityStateEntry API gebruikt, kunt u alleen de tijd op de voorgrond meten. Zo krijgt u een betere statistiek voor gebruikersengagement.
Berekening van tijd op de voorgrond implementeren
De PerformanceTimeline API toont wijzigingen in de zichtbaarheidsstatus als prestatie-items. In plaats van te reageren op visibilitychange-gebeurtenissen en handmatig tijd te verzamelen tijdens een sessie, kunt u op elk moment de hele zichtbaarheidsgeschiedenis opvragen.
VERPLICHT: Je moet de visibility-state-prestatie-items opvragen om de werkelijke tijd op de voorgrond te berekenen.
/**
* Calculates total time the page was in the visible state.
*
* @returns {number} Total foreground time in milliseconds.
*/
function getTotalForegroundTime() {
// MANDATORY: Query the visibility-state entries from the performance timeline.
const entries = performance.getEntriesByType('visibility-state');
// Fallback: If the browser does not support VisibilityStateEntry,
// the API will gracefully return an empty array.
if (entries.length === 0) {
// Return total time since navigation start as a fallback.
return performance.now();
}
let totalForegroundTime = 0;
for (let i = 0; i < entries.length; i++) {
// Only calculate duration for periods where the state was 'visible'
if (entries[i].name === 'visible') {
const start = entries[i].startTime;
// The end time is the start time of the next state change,
// or the current time if this is the final entry.
const end = i + 1 < entries.length
? entries[i + 1].startTime
: performance.now();
totalForegroundTime += (end - start);
}
}
return totalForegroundTime;
}
Fallbacks en browserondersteuning
De VisibilityStateEntry API is een moderne toevoeging aan de Performance Timeline en wordt misschien niet in alle browsers ondersteund.
Omdat performance.getEntriesByType('visibility-state') een lege array retourneert in niet-ondersteunde browsers, is functiedetectie ingebouwd in de berekeningsstroom. Controleer altijd of er items worden geretourneerd voordat je verdergaat.
Als de API niet wordt ondersteund, is de aanbevolen reserveoptie om performance.now() te retourneren. Dit is de totale tijd sinds de navigatie, wat een redelijke bovengrens is voor de engagementduur als de geschiedenis van de zichtbaarheidsstatus niet beschikbaar is.
const entries = performance.getEntriesByType('visibility-state');
// If the array is empty, the API is likely unsupported.
if (entries.length === 0) {
// Fallback: Return total time since page load.
return performance.now();
}