如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

2023年2月14日12:02:13 评论 1,028
Ga4监测网站速度(页面加载速度),实现和ua近似的功能。
UA落幕,不管想不想用Ga4都要被升级了,可惜Ga4为了把手机App也包含进来,对统计逻辑做了大幅改变。好多还停留在独立站阶段的伙伴们只能自我奋斗了。
技术迭代,大势所趋,我们这种非技术专业的玩家早晚会被慢慢抛弃的。困兽犹斗,能多奋斗几天,就都奋斗几天,被淘汰了,我们就去写网络小说。
大神们都写好了,抄就可以了
附件里有中英文两版,代码差不多,东灵君按英文版部署的。效果不错。
对于数据报告,哎,Ga4实在不敢恭维,难用。而且对于这一组时间相关的指标,收集的数据大部分需要自己换算。
英文版的提到了另一个工具,现在叫looker studio,可以自定义表格,还可以自行加减乘除地指标进行计算。配合这个东西,就可以完美实现UA原来的功能。
注意,附录2中提到的事件数,要做细分,performance_time才是需要的。计算均值要用这个做分母。
如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析
lookerstudio.google.com
looker studio多少也需要花些时间去学习。
如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析
再次重复一下指标的含义,未经处理的都是按ms毫秒计算的。UA里会自动换算成秒,g
a4的不会。
https://support.google.com/analytics/answer/2383341?hl=en&ref_topic=1282106#zippy=%2Cin-this-article

Page Timings report > Explorer & Map Overlay tabs > DOM Timings subtab

  • Pageviews : The number of times the page was viewed during the selected date range.
  • Avg. Document Interactive Time : The average time (in seconds) that the browser takes to parse the document (DOMInteractive), including the network time from the user's location to your server. At this time, the user can interact with the Document Object Model even though it is not fully loaded.
  • Avg. Document Content Loaded Time : The average time (in seconds) that the browser takes to parse the document and execute deferred and parser-inserted scripts (DOMContentLoaded), including the network time from the user's location to your server. Parsing of the document is finished, the Document Object Model is ready, but referenced style sheets, images, and subframes may not be finished loading. This event is often the starting point for javascript framework execution, e.g., JQuery's onready() callback, etc.
  • Avg Page Load Time : The average amount of time (in seconds) it takes that page to load, from initiation of the pageview (e.g., click on a page link) to load completion in the browser.

    Avg. Page Load Time consists of two components: 1) network and server time, and 2) browser time. The Technical section of the Explorer tab provides details about the network and server metrics. The remaining time is the browser overhead for parsing and executing the JavaScript and rendering the page.

Learn more about the Navigation Timing API, and these specific timing attributes.

If these metrics sometimes indicate longer page-load times than you otherwise observe, it is due to the number of samples taken over the date range you are using.

附件

英文版的

https://www.thyngster.com/performance-timing-tracking-with-google-analytics-4#custom-metrics-definition-in-google-analytics-4

I'm really obsessed with performance, while I may not be the best on that task I'm a real tryhard on that topic, at least up to where my knowledge allows me. And this said, I really miss the Site Speed Report on Google Analytics 4.

This is why I replicated the current metrics and logic from Universal Analytics, and I sharing it with you on this post. If you end implementing this tracking you'll have the following metrics avaiable in for your use, for example in data studio.

The current provided code, will even allow you to set a siteSpeedSampleRate as Universal Analytics.

Code Snippet


<script>
(function() {

    var siteSpeedSampleRate = 100;
    var gaCookiename = '_ga';
    var dataLayerName = 'dataLayer';

    // No need to edit anything after this line
    var shouldItBeTracked = function(siteSpeedSampleRate) {
        // If we don't pass a sample rate, default value is 1
        if (!siteSpeedSampleRate)
            siteSpeedSampleRate = 1;
        // Generate a hashId from a String
        var hashId = function(a) {
            var b = 1, c;
            if (a)
                for (b = 0,
                c = a.length - 1; 0 <= c; c--) {
                    var d = a.charCodeAt(c);
                    b = (b << 6 & 268435455) + d + (d << 14);
                    d = b & 266338304;
                    b = 0 != d ? b ^ d >> 21 : b
                }
            return b
        }
        var clientId = ('; ' + document.cookie).split('; '+gaCookiename+'=').pop().split(';').shift().split(/GA1\.[0-9]\./)[1];
        if(!clientId) return !1;
        // If, for any reason the sample speed rate is higher than 100, let's keep it to a 100 max value
        var b = Math.min(siteSpeedSampleRate, 100);        
        return hashId(clientId) % 100 >= b ? !1 : !0
    }

    if (shouldItBeTracked(siteSpeedSampleRate)) {
        var pt = window.performance || window.webkitPerformance;
        pt = pt && pt.timing;
        if (!pt)
            return;
        if (pt.navigationStart === 0 || pt.loadEventStart === 0)
            return;
        var timingData = {
            "page_load_time": pt.loadEventStart - pt.navigationStart,
            "page_download_time": pt.responseEnd - pt.responseStart,
            "dns_time": pt.domainLookupEnd - pt.domainLookupStart,
            "redirect_response_time": pt.fetchStart - pt.navigationStart,
            "server_response_time": pt.responseStart - pt.requestStart,
            "tcp_connect_time": pt.connectEnd - pt.connectStart,
            "dom_interactive_time": pt.domInteractive - pt.navigationStart,
            "content_load_time": pt.domContentLoadedEventStart - pt.navigationStart
        };
        // Sanity Checks if any value is negative abort
        if (Object.values(timingData).filter(function(e) {
            if (e < 0)
                return e;
        }).length > 0)
            return;
        window[dataLayerName] && window[dataLayerName].push({
            "event": "performance_timing",
            "timing": timingData
        })
    }
}
)() 
</script>    

Setting up GTM

The first thing we need to do it adding the following code snippet above in a Custom HTML tag in Google Tag Manager, that fired on the Window Load event.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

Outcome

The code we added above will kindly push all the performance timing data in a nicely formated dataLayer push, that we later use to pass the data to any tag/vendor we want. In our case we'll pushing the data to a GA4 event tag.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

 


{
    event: 'performance_timing',
    timing: {
        page_load_time: 131,
        page_download_time: 0,
        dns_time: 0,
        redirect_response_time: 1,
        server_response_time: 34,
        tcp_connect_time: 0,
        dom_interactive_time: 63,
        content_load_time: 63
    }
} 

Setting GA4 Event Tag

Now that we have all the data being push to the dataLayer, we'll need to create a new GA4 event Tag and maps all the data accordingly, please refer to the following screenshot for all the details.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

Custom Metrics definition in Google Analytics 4

As you already know, sending a parameter within an event doesn't mean anything until we map it to a dimension within our property.

For this we need to go to the Custom Definitions > Custom Metrics, and add all this new parameters with the event scope and Milliseconds as the Unit of Measurement.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

 

How to view the data

Now that we started collecting the data, we have some different ways to view it, we could use the GA4 reports ( which will be limiting the reporting possibilities a lot )

Using the Google Analytics Exploration

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

Using Data Studio

This is my prefered option, you can create AVG metrics in an easy way, AVG metrics in Seconds to match the reports on Universal Analytics.

For example, I tried to quickly replicate the Universal Site Speed reports using Data Studio without almost no time.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

Using Big Query

Lastly, if you're one of the brave analysts around the world, the good news is that the possibilities are now almost enless, is just up to you to play around with this and paint it anywhere you want.

As a simple example, let's find out how many and which pages took more than 1 second to load.


SELECT * ,
   FROM `thyngster.*********.events_20220712`
   WHERE event_name = "performance_timing" AND 
   (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'page_load_time') > 1000 

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

Metrics List

Here it goes the list of metrics you can configure and use to replicate the old Universal Analytics reports:

  • Site Speed Events Count
  • Page Load Time (ms) and Avg. Page Load Time (sec)
  • Domain Lookup Time (ms) and Avg. Domain Lookup Time (sec)
  • Page Download Time (ms) and Avg. Page Download Time (sec)
  • Redirection Time (ms) and Avg. Redirection Time (sec)
  • Server Connection Time (ms) and Avg. Server Connection Time (sec)
  • Server Response Time (ms) and Avg. Server Response Time (sec)
  • Document Interactive Time (ms) and Avg. Document Interactive Time
  • Document Content Loaded Time (ms) Avg. Document Content Loaded Time (sec)

(Extra) How siteSpeedSample Works

I must confess I've never looked at this and I found pretty curious about how Universal Analytics was doing the Site Speed Sampling. I was expecting having it doing a sampling based on hit, but currently the sampling is done on users ( devices ).

This means that rather than getting details about a 5% of the pageviews, you're getting the details about the 5% of your visitors instead.

Universal Analytics has been relying on the clientId value to determine if the current user should be sending the timing details.

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

中文版的

https://www.ichdata.com/gets-the-exact-load-time-of-the-page-google-analytics.html

原理是,页面打开的时候,用自定义JavaScript从浏览器获取页面打开过程中的各个时间,然后通过DataLayer发送出去,再GTM上触发,发送给Google Analytics 4

GTM配置过程

GTM上配置监听代码

在GTM中点击「代码」——「新建」——「选择一个代码类型以开始设置…」——「自定义HTML」,然后命名为“THML time”,做如下设置:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

这段代码的作用是页面加载的时候,从浏览器获取页面加载时间数据。

源码:

  1. <script>
  2. (function() {
  3.  
  4. var siteSpeedSampleRate = 100;
  5. var gaCookiename = '_ga';
  6. var dataLayerName = 'dataLayer';
  7.  
  8. // No need to edit anything after this line
  9. var shouldItBeTracked = function(siteSpeedSampleRate) {
  10. // If we don't pass a sample rate, default value is 1
  11. if (!siteSpeedSampleRate)
  12. siteSpeedSampleRate = 1;
  13. // Generate a hashId from a String
  14. var hashId = function(a) {
  15. var b = 1, c;
  16. if (a)
  17. for (b = 0,
  18. c = a.length - 1; 0 <= c; c--) {
  19. var d = a.charCodeAt(c);
  20. b = (b << 6 & 268435455) + d + (d << 14); d = b & 266338304; b = 0 != d ? b ^ d >> 21 : b
  21. }
  22. return b
  23. }
  24. var clientId = ('; ' + document.cookie).split('; '+gaCookiename+'=').pop().split(';').shift().split(/GA1\.[0-9]\./)[1];
  25. if(!clientId) return !1;
  26. // If, for any reason the sample speed rate is higher than 100, let's keep it to a 100 max value
  27. var b = Math.min(siteSpeedSampleRate, 100);
  28. return hashId(clientId) % 100 >= b ? !1 : !0
  29. }
  30.  
  31. if (shouldItBeTracked(siteSpeedSampleRate)) {
  32. var pt = window.performance || window.webkitPerformance;
  33. pt = pt && pt.timing;
  34. if (!pt)
  35. return;
  36. if (pt.navigationStart === 0 || pt.loadEventStart === 0)
  37. return;
  38. var timingData = {
  39. "page_load_time": pt.loadEventStart - pt.navigationStart,
  40. "page_download_time": pt.responseEnd - pt.responseStart,
  41. "dns_time": pt.domainLookupEnd - pt.domainLookupStart,
  42. "redirect_response_time": pt.fetchStart - pt.navigationStart,
  43. "server_response_time": pt.responseStart - pt.requestStart,
  44. "tcp_connect_time": pt.connectEnd - pt.connectStart,
  45. "dom_interactive_time": pt.domInteractive - pt.navigationStart,
  46. "content_load_time": pt.domContentLoadedEventStart - pt.navigationStart
  47. };
  48. // Sanity Checks if any value is negative abort
  49. if (Object.values(timingData).filter(function(e) {
  50. if (e < 0) return e; }).length > 0)
  51. return;
  52. window[dataLayerName] && window[dataLayerName].push({
  53. "event": "performance_timing",
  54. "timing": timingData
  55. })
  56. }
  57. }
  58. )()
  59. </script>

GTM上配置GA4事件跟踪

接下来是先配置获取数据层里的数据层变量和自订事件,然后配置代码。

配置变量

数据层变量有 page_load_time、page_download_time、dns_time、redirect_response_time、server_response_time、tcp_connect_time、dom_interactive_time、content_load_time

以为page_load_time为例,在GTM中点击「变量」——「新建」——「选择一个变量类型以开始设置…」——「数据层变量」,然后命名为“page_load_time”,做如下设置:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

同理配置其他几个数据层变量:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

配置触发器

自定义事件只要一个,是performance_timing

在GTM中点击「触发器」——「新建」——「选择一个触发器类型以开始设置…」——「自定义事件」,然后命名为“performance_timing”,做如下设置:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

配置代码

最后就是配置GA4事件,在GTM中点击「变量」——「新建」——「选择一个代码类型以开始设置…」——「Google Analytics(分析):GA4 事件」,然后命名为“GA Page performance_timing”,做如下设置:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

事件名称命名为“performance_timing”,事件参数都是数据层变量里的。

预览调试

配置好后,在GTM上预览调试,调试没问题就可以发布出去收集数据。

 

GA4上注册事件参数

事件参数里的所有参数都需要在GA4里注册,才可以使用。

以page_load_time为例,在GA4中点击「管理」——「自定义设置」——「自定义指标」——「创建自定义维度」,然后做如下设置:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

 

需要注意,这里的衡量单位是毫秒。

同理注册其他的事件参数即可。

 

查看数据

可以在探索里查看数据:

如何使用 Google Analytics 4(ga4) 进行网页性能分析,页面加载速度,响应速度的分析

 

这里的单位是毫秒,数值是加总的,如果要看页面平均时间是多少秒,需要用总时间除以事件数,再除以1000。

  • 君子仁爱:取之有道。刷新有惊喜,看头像。
  • 原创不易,转载注明出处和链接:https://acg.92ylq.com/anime/ga4-sitespeed/
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: