减少网页加载时间可改善网站的整体用户体验。本页介绍如何将用户计时信息发送给 Google Analytics(分析)。
实现
使用 event
命令发送一个 timing_complete
事件:
gtag('event', 'timing_complete', {<timing_parameters>});
其中 <timing_parameters> 是一个或多个“参数-值”对。每个参数-值对之间用英文逗号分隔。例如,以下命令会向 Google Analytics(分析)发送用户计时事件,指明当前网页加载其所有外部 JavaScript 依赖关系耗时 3549 毫秒:
gtag('event', 'timing_complete', {
'name' : 'load',
'value' : 3549,
'event_category' : 'JS Dependencies'
});
用户计时参数
下表对各用户计时参数进行了概要说明:
参数名称 | 数据类型 | 必需 | 说明 |
---|---|---|---|
name |
string |
是 |
用于标识要记录的变量的字符串(例如 'load' )。
|
value |
integer |
是 |
向 Google Analytics(分析)报告的以毫秒为单位的历时时间(例如 20 )。
|
event_category |
string |
否 |
用于将所有用户计时变量归类到相应逻辑组的字符串(例如 'JS Dependencies' )。
|
event_label |
string |
否 |
可用于提高报告中显示用户计时数据灵活性的字符串(例如 'Google CDN' )。
|
衡量时间
timing_complete
事件需要一个 value
参数,用于以毫秒为单位指定已用时间。您需要编写采集此值的代码。
最简单的方法是在时间段的开头创建时间戳,然后在时间段的结尾创建另一个时间戳。然后,计算时间戳之间所用时间。
大多数新型浏览器都支持 Navigation Timing API,该 API 针对 window.performance 对象提供了一些方法,可通过高精度时间数据来衡量网页性能。
下例使用了 performance.now()
方法,该方法返回从网页最初开始加载到目前为止的时长:
// Feature detects Navigation Timing API support.
if (window.performance) {
// Gets the number of milliseconds since page load
// (and rounds the result since the value must be an integer).
var timeSincePageLoad = Math.round(performance.now());
// Sends the timing event to Google Analytics.
gtag('event', 'timing_complete', {
'name': 'load',
'value': timeSincePageLoad,
'event_category': 'JS Dependencies'
});
}
有关采样的注意事项
Google Analytics(分析)将对计时事件进行抽样,以确保针对此功能公平分配系统资源。
计时事件的抽样率取决于系统针对相应媒体资源在前一天所接收到的网页浏览总数。下表简要说明了计时抽样率的确定方式:
网页浏览总数(前一天) | 系统最多可处理的计时事件数 |
---|---|
0 - 1000 | 100 |
1000 - 100000 | 网页浏览总数的 10% |
100000 - 1000000 | 10000 |
1000000+ | 网页浏览总数的 1% |