במדריך הזה מוסבר איך לחשב במדויק את משך הזמן הכולל שבו משתמש צופה באופן פעיל בדף. מדדים מסורתיים כמו זמן ביקור ממוצע כוללים לעיתים קרובות באופן שגוי את הזמן שבו הדף היה פתוח ברקע. באמצעות ה-API של VisibilityStateEntry, אפשר למדוד רק את "הזמן בחזית", וכך לקבל מדד טוב יותר של התעניינות המשתמשים.
הטמעת חישוב הזמן בחזית
PerformanceTimeline API חושף שינויים במצב החשיפה כרשומות ביצועים. במקום להגיב לאירועי visibilitychange ולצבור זמן באופן ידני במהלך סשן, אתם יכולים לשלוח שאילתה על כל היסטוריית החשיפה בכל שלב.
חובה: צריך לשלוח שאילתה לרשומות הביצועים של visibility-state כדי לחשב את הזמן האמיתי בחזית.
/**
* 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;
}
חלופות ותמיכה בדפדפנים
VisibilityStateEntry API הוא תוספת מודרנית ל-Performance Timeline, ויכול להיות שהוא לא נתמך בכל הדפדפנים.
מכיוון שהפונקציה performance.getEntriesByType('visibility-state') מחזירה מערך ריק בדפדפנים לא נתמכים, זיהוי התכונות מובנה בתהליך החישוב. תמיד צריך לבדוק אם מוחזרות רשומות לפני שממשיכים.
אם ה-API לא נתמך, מומלץ להחזיר את הערך performance.now() כברירת מחדל. הערך הזה מייצג את משך הזמן הכולל מאז הניווט, והוא משמש כגבול עליון סביר לזמן ההתעניינות כשההיסטוריה של מצב החשיפה לא זמינה.
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();
}