Google Analytics分析始终将“平均网页加载时间”显示为零

问题描述

我的Google Analytics(分析)脚本是这样的

    < !--Global site tag(gtag.js) - Google Analytics-- >
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxx-x"></ script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js',new Date());
     gtag('config','UA-xxxxxxx-x',{ 'page_path': curpath });
    </script>

Thiw正常运行,除非Avg. Page Load Time登录分析(始终显示为零)。我在这里想念什么? 注意:我的网站可以在具有单个URL的ajax调用上运行

解决方法

由于使用了AJAX调用,因此浏览器缺少必要的信息。

Google Analytics(分析)使用了导航定时API,该API相当可靠,因为实际的测量是由浏览器完成的,并且这些值可以作为window.performance.timing对象的属性读取。

Example from here

Calculate the total page load time

    const perfData = window.performance.timing; 
    const pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;

您的Ajax调用不会填充这些值(从某种意义上讲,因为相应的DOM事件未在AJAX调用中填充),因此GA无法记录页面加载时间。

您可以自定义user timings in GA. They will be limited to a sample of 1% of your calls max,然后从那里推断平均值。您将在您的Ajax调用开始到响应呈现的时间点之间传递增量。