Google Analytics异步设计模式的名称是什么?它在哪里使用?

时间:2021-07-08 15:19:58

Google Analytics async code uses a very distinct design pattern for javascript code execution.

Google Analytics异步代码使用非常独特的设计模式来执行javascript代码。

The code depends on a library and it doesn't know if the library has loaded or not. If the library didn't load yet it just queues all the commands into an Array object. When the library loads it just creates the _gaq object and executes all commands in the sequence it was included. It then overwrites the push function so future commands are executed right away.

代码依赖于库,并且不知道库是否已加载。如果库尚未加载,则只将所有命令排队到Array对象中。当库加载它时,它只是创建_gaq对象并按照它包含的顺序执行所有命令。然后它会覆盖推送功能,以便立即执行将来的命令。

The idea is to make the commands run very fast when they are queued. The code is only really evaluated later when the library is loaded.

这个想法是让命令在排队时运行得非常快。只有在加载库时才会对代码进行真正的评估。

They also load the library with a parameters async=true. This causes almost no impact on the actual page loading time.

他们还使用参数async = true加载库。这几乎不会对实际页面加载时间产生影响。

The commands look just like the sync versions of it, but the first string is a function name and the next parameters are that function parameters. You can also push functions into this array and the functions will be executed in sequence as well with a null context. So if you need to do something synchronous with the library you can push a function to do this inside _gaq.

命令看起来就像它的同步版本,但第一个字符串是函数名称,接下来的参数是函数参数。您还可以将函数推送到此数组中,函数也将按顺序执行,并使用空上下文。因此,如果您需要与库同步,可以在_gaq中推送一个函数来执行此操作。

I think this is a very clever solution but I have never seen it before. Does anyone know the name of this design pattern or where it's used besides the Google Analytics tracking code?

我认为这是一个非常聪明的解决方案,但我以前从未见过它。除Google Analytics跟踪代码外,有谁知道此设计模式的名称或其使用位置?

4 个解决方案

#1


42  

I've referred to it as "asynchronous function queuing", but its not quite a catchy name, and certainly not the formal name of the design pattern.

我把它称为“异步函数排队”,但它不是一个吸引人的名字,当然也不是设计模式的正式名称。

What's interesting is that, though I hadn't seen this particular pattern used before, since Google adopted it for Google Analytics, its been adopted widely by different platforms looking to nab the asynchronous juice (Disqus comes to mind.)

有趣的是,尽管我之前没有看过这种特殊的模式,但是谷歌将其用于谷歌分析,它已经被不同平台广泛采用,希望能够获得异步果汁(想到了这一点)。

This blog post is the most in-depth examination of the async Google Analytics syntax I've read, and includes a fairly detailed explanation of how the one can replicate the pattern:

这篇博文是我读过的异步Google Analytics语法的最深入的考察,并且包含了一个如何复制模式的相当详细的解释:

From the blog post:

来自博文:

var GoogleAnalyticsQueue = function () {

    this.push = function () {
        for (var i = 0; i < arguments.length; i++) try {
            if (typeof arguments[i] === "function") arguments[i]();
            else {
                // get tracker function from arguments[i][0]
                // get tracker function arguments from arguments[i].slice(1)
                // call it!  trackers[arguments[i][0]].apply(trackers, arguments[i].slice(1));
            }
        } catch (e) {}
    }

    // more code here…
};

// get the existing _gaq array
var _old_gaq = window._gaq;

// create a new _gaq object
window._gaq = new GoogleAnalyticsQueue();

// execute all of the queued up events - apply() turns the array entries into individual arguments
window._gaq.push.apply(window._gaq, _old_gaq);

It also notes that, even though not many browsers support the async attribute, the method of injection used makes the script load asynchronously in most browsers, and includes a helpful chart:

它还指出,即使没有多少浏览器支持async属性,使用的注入方法也会使脚本在大多数浏览器中异步加载,并包含一个有用的图表:

Google Analytics异步设计模式的名称是什么?它在哪里使用?

#2


3  

All it's doing is pushing data into a global array

它所做的只是将数据推送到全局数组中

var _qaq = _qaq || [];
_qaq.push(stuff);

It basically allows you to buffer up data to deal with before the library has loaded.

它基本上允许您在库加载之前缓冲数据以进行处理。

The main reason this pattern isn't used much is that other libraries generally need the resources to load before they can do anything. It wouldn't make any sense to start buffering jQuery commands.

这种模式使用不多的主要原因是其他库通常需要在可以执行任何操作之前加载资源。开始缓冲jQuery命令没有任何意义。

It's not a pattern it's simply storing data in global scope and saying it's some-one elses job to process this, I don't care when you process it.

这不是一种模式,它只是简单地将数据存储在全球范围内,并说它是处理这个问题的一部分工作,我不在乎你何时处理它。

However it is a clever way to deal with the fact you don't know when something is loaded or ready, the common alternative is a DOMReady block.

然而,这是一个聪明的方法来处理你不知道何时加载或准备好的事实,常见的替代方案是DOMReady块。

#3


3  

A good writeup of javascript loading stratgies is available here http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

这里有一个很好的javascript加载策略文章http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

And as far as I recall, ga.js async syntax has been inspired by Steve Souders. You can look at ControlJS , one of his projects

据我所知,ga.js的异步语法受到了Steve Souders的启发。您可以查看ControlJS,他的一个项目

#4


1  

In 2014 Ilya Grigorik wrote a post titled Script-injected "async scripts" considered harmful. That post links to this question and uses the phrase "asynchronous function queuing" as the name of the design pattern used by Google Analytics.

2014年,Ilya Grigorik写了一篇题为脚本注入的“异步脚本”的帖子被认为是有害的。该帖子链接到此问题,并使用短语“异步函数排队”作为Google Analytics使用的设计模式的名称。

Async function queuing differs from more recent design patterns like Fetch Injection, which don't require or need a globally defined queue. Here's an example of Fetch Injection implemented in the Fetch Inject module and used to asynchronously download resources in a document:

异步函数排队与更新的设计模式(如Fetch Injection)不同,后者不需要或不需要全局定义的队列。以下是Fetch Inject模块中实现的Fetch Injection示例,用于异步下载文档中的资源:

Google Analytics异步设计模式的名称是什么?它在哪里使用?

Notice the Fetch Injection design pattern is capable of loading CSS in addition to JavaScript in parallel, eliminating the blocking behavior of CSSOM and the Web Font download, greatly reducing perceived latency. Script execution order is fully preserved using an easy-to-understand API, making it simple to manage loading complex groups of resources with total programmatic control.

请注意,Fetch Injection设计模式除了支持JavaScript之外还能够加载CSS,消除了CSSOM的阻塞行为和Web字体下载,大大减少了感知延迟。使用易于理解的API可以完全保留脚本执行顺序,从而可以通过完全的程序控制轻松管理复杂的资源组。

#1


42  

I've referred to it as "asynchronous function queuing", but its not quite a catchy name, and certainly not the formal name of the design pattern.

我把它称为“异步函数排队”,但它不是一个吸引人的名字,当然也不是设计模式的正式名称。

What's interesting is that, though I hadn't seen this particular pattern used before, since Google adopted it for Google Analytics, its been adopted widely by different platforms looking to nab the asynchronous juice (Disqus comes to mind.)

有趣的是,尽管我之前没有看过这种特殊的模式,但是谷歌将其用于谷歌分析,它已经被不同平台广泛采用,希望能够获得异步果汁(想到了这一点)。

This blog post is the most in-depth examination of the async Google Analytics syntax I've read, and includes a fairly detailed explanation of how the one can replicate the pattern:

这篇博文是我读过的异步Google Analytics语法的最深入的考察,并且包含了一个如何复制模式的相当详细的解释:

From the blog post:

来自博文:

var GoogleAnalyticsQueue = function () {

    this.push = function () {
        for (var i = 0; i < arguments.length; i++) try {
            if (typeof arguments[i] === "function") arguments[i]();
            else {
                // get tracker function from arguments[i][0]
                // get tracker function arguments from arguments[i].slice(1)
                // call it!  trackers[arguments[i][0]].apply(trackers, arguments[i].slice(1));
            }
        } catch (e) {}
    }

    // more code here…
};

// get the existing _gaq array
var _old_gaq = window._gaq;

// create a new _gaq object
window._gaq = new GoogleAnalyticsQueue();

// execute all of the queued up events - apply() turns the array entries into individual arguments
window._gaq.push.apply(window._gaq, _old_gaq);

It also notes that, even though not many browsers support the async attribute, the method of injection used makes the script load asynchronously in most browsers, and includes a helpful chart:

它还指出,即使没有多少浏览器支持async属性,使用的注入方法也会使脚本在大多数浏览器中异步加载,并包含一个有用的图表:

Google Analytics异步设计模式的名称是什么?它在哪里使用?

#2


3  

All it's doing is pushing data into a global array

它所做的只是将数据推送到全局数组中

var _qaq = _qaq || [];
_qaq.push(stuff);

It basically allows you to buffer up data to deal with before the library has loaded.

它基本上允许您在库加载之前缓冲数据以进行处理。

The main reason this pattern isn't used much is that other libraries generally need the resources to load before they can do anything. It wouldn't make any sense to start buffering jQuery commands.

这种模式使用不多的主要原因是其他库通常需要在可以执行任何操作之前加载资源。开始缓冲jQuery命令没有任何意义。

It's not a pattern it's simply storing data in global scope and saying it's some-one elses job to process this, I don't care when you process it.

这不是一种模式,它只是简单地将数据存储在全球范围内,并说它是处理这个问题的一部分工作,我不在乎你何时处理它。

However it is a clever way to deal with the fact you don't know when something is loaded or ready, the common alternative is a DOMReady block.

然而,这是一个聪明的方法来处理你不知道何时加载或准备好的事实,常见的替代方案是DOMReady块。

#3


3  

A good writeup of javascript loading stratgies is available here http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

这里有一个很好的javascript加载策略文章http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

And as far as I recall, ga.js async syntax has been inspired by Steve Souders. You can look at ControlJS , one of his projects

据我所知,ga.js的异步语法受到了Steve Souders的启发。您可以查看ControlJS,他的一个项目

#4


1  

In 2014 Ilya Grigorik wrote a post titled Script-injected "async scripts" considered harmful. That post links to this question and uses the phrase "asynchronous function queuing" as the name of the design pattern used by Google Analytics.

2014年,Ilya Grigorik写了一篇题为脚本注入的“异步脚本”的帖子被认为是有害的。该帖子链接到此问题,并使用短语“异步函数排队”作为Google Analytics使用的设计模式的名称。

Async function queuing differs from more recent design patterns like Fetch Injection, which don't require or need a globally defined queue. Here's an example of Fetch Injection implemented in the Fetch Inject module and used to asynchronously download resources in a document:

异步函数排队与更新的设计模式(如Fetch Injection)不同,后者不需要或不需要全局定义的队列。以下是Fetch Inject模块中实现的Fetch Injection示例,用于异步下载文档中的资源:

Google Analytics异步设计模式的名称是什么?它在哪里使用?

Notice the Fetch Injection design pattern is capable of loading CSS in addition to JavaScript in parallel, eliminating the blocking behavior of CSSOM and the Web Font download, greatly reducing perceived latency. Script execution order is fully preserved using an easy-to-understand API, making it simple to manage loading complex groups of resources with total programmatic control.

请注意,Fetch Injection设计模式除了支持JavaScript之外还能够加载CSS,消除了CSSOM的阻塞行为和Web字体下载,大大减少了感知延迟。使用易于理解的API可以完全保留脚本执行顺序,从而可以通过完全的程序控制轻松管理复杂的资源组。