What's the name of Google Analytics async design pattern and where is it used?

前端 未结 4 1126
[愿得一人]
[愿得一人] 2020-12-12 10:38

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

The code depends on a library and it doesn\'t know if the library has

4条回答
  •  盖世英雄少女心
    2020-12-12 11:13

    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:

    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:

    enter image description here

提交回复
热议问题