Toplam ön plan süresini hesaplama

Bu kılavuzda, bir kullanıcının bir sayfayı aktif olarak görüntülemek için harcadığı toplam sürenin nasıl doğru şekilde hesaplanacağı ayrıntılı olarak açıklanmaktadır. Sayfada geçirilen süre gibi geleneksel metrikler, genellikle sayfanın arka planda açık olduğu süreyi yanlış bir şekilde dahil eder. VisibilityStateEntry API'sini kullanarak yalnızca "ön plan süresini" ölçebilir ve kullanıcı etkileşimiyle ilgili daha iyi bir metrik elde edebilirsiniz.

Ön plan süresi hesaplamasını uygulama

PerformanceTimeline API'si, görünürlük durumu değişikliklerini performans girişleri olarak gösterir. visibilitychange etkinliklerine tepki vermek ve bir oturum boyunca manuel olarak zaman biriktirmek yerine, görünürlük geçmişinin tamamını istediğiniz zaman sorgulayabilirsiniz.

ZORUNLU: Gerçek ön plan süresini hesaplamak için visibility-state performans girişlerini sorgulamanız gerekir.

/**
 * 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;
}

Yedekler ve tarayıcı desteği

VisibilityStateEntry API, performans zaman çizelgesine yapılan modern bir eklemedir ve tüm tarayıcılarda desteklenmeyebilir.

performance.getEntriesByType('visibility-state'), desteklenmeyen tarayıcılarda boş bir dizi döndürdüğünden özellik algılama, hesaplama akışına yerleştirilmiştir. Devam etmeden önce her zaman girişlerin döndürülüp döndürülmediğini kontrol etmeniz gerekir.

API desteklenmiyorsa önerilen yedek, performance.now() değerini döndürmektir. Bu, gezinmeden sonraki toplam süreyi temsil eder ve görünürlük durumu geçmişi kullanılamadığında etkileşim süresi için makul bir üst sınır görevi görür.

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();
}