คำนวณเวลาที่ใช้ในเบื้องหน้ารวม

คู่มือนี้จะอธิบายวิธีคำนวณเวลาทั้งหมดที่ผู้ใช้ใช้ในการดูหน้าเว็บอย่างถูกต้อง เมตริกแบบเดิม เช่น เวลาบนหน้าเว็บ มักจะรวมเวลาที่ใช้กับหน้าเว็บในเบื้องหลังอย่างไม่ถูกต้อง เมื่อใช้ VisibilityStateEntry API คุณจะวัดได้เฉพาะ "เวลาที่อยู่เบื้องหน้า" ซึ่งจะให้เมตริกการมีส่วนร่วมของผู้ใช้ที่ดีกว่า

การใช้การคำนวณเวลาที่ทำงานอยู่เบื้องหน้า

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