为什么Segment.io loader脚本将方法名称/ args推送到看似被覆盖的队列?

Mar*_*ell 8 javascript asynchronous segment-io

我一直在剖析以下代码片段,它用于异步加载Segment.io分析包装器脚本:

// Create a queue, but don't obliterate an existing one!
var analytics = analytics || [];

// Define a method that will asynchronously load analytics.js from our CDN.
analytics.load = function(apiKey) {

    // Create an async script element for analytics.js.
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') +
                  'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.min.js';

    // Find the first script element on the page and insert our script next to it.
    var firstScript = document.getElementsByTagName('script')[0];
    firstScript.parentNode.insertBefore(script, firstScript);

    // Define a factory that generates wrapper methods to push arrays of
    // arguments onto our `analytics` queue, where the first element of the arrays
    // is always the name of the analytics.js method itself (eg. `track`).
    var methodFactory = function (type) {
        return function () {
            analytics.push([type].concat(Array.prototype.slice.call(arguments, 0)));
        };
    };

    // Loop through analytics.js' methods and generate a wrapper method for each.
    var methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick',
                   'trackSubmit', 'pageview', 'ab', 'alias', 'ready'];

    for (var i = 0; i < methods.length; i++) {
        analytics[methods[i]] = methodFactory(methods[i]);
    }
};

// Load analytics.js with your API key, which will automatically load all of the
// analytics integrations you've turned on for your account. Boosh!
analytics.load('MYAPIKEY');
Run Code Online (Sandbox Code Playgroud)

它评论很好,我可以看到它正在做什么,但是当涉及到methodFactory函数时,我感到很困惑,该函数推动了在主analytics.js脚本加载到全局analytics数组之前进行的任何方法调用的细节(方法名称和参数).

这是一切都很好,但随后如果/当主脚本负载,它似乎只是覆盖全球analytics变量(见这里最后一行),因此所有数据都将丢失.

我看到这是如何通过截断尚不存在的方法来防止网页中的脚本错误,但我不明白为什么存根不能只返回一个空函数:

var methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick',
               'trackSubmit', 'pageview', 'ab', 'alias', 'ready'];

for (var i = 0; i < methods.length; i++) {
    lib[methods[i]] = function () { };
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?拜托,帮帮我理解!

Ian*_*lor 24

Ian在这里,Segment.io的联合创始人 - 我实际上并没有写那个代码,Calvin做了,但是我可以告诉你它正在做什么.

你是对的,methodFactory正在剔除方法,以便在脚本加载之前它们可用,这意味着人们可以在analytics.track没有将这些调用包装在一个if或调用中的情况下ready()调用.

但是这些方法实际上比"哑"存根更好,因为它们保存了被调用的方法,因此我们可以稍后重放这些操作.这就是这个部分:

analytics.push([type].concat(Array.prototype.slice.call(arguments, 0)));
Run Code Online (Sandbox Code Playgroud)

为了使其更具可读性:

var methodFactory = function (method) {
    return function () {
        var args = Array.prototype.slice.call(arguments, 0);
        var newArgs = [method].concat(args);
        analytics.push(newArgs);
    };
};
Run Code Online (Sandbox Code Playgroud)

它解决了被调用方法的名称,这意味着如果我analytics.identify('userId'),我们的队列实际上得到一个如下所示的数组:

['identify', 'userId']
Run Code Online (Sandbox Code Playgroud)

然后,当我们的库加载时,它卸载所有排队的调用并将它们重放到实际方法(现在可用)中,以便仍然保留在加载之前记录的所有数据.这是关键部分,因为我们不想丢弃在我们的库有机会加载之前发生的任何调用.看起来像这样:

// Loop through the interim analytics queue and reapply the calls to their
// proper analytics.js method.
while (window.analytics.length > 0) {
    var item = window.analytics.shift();
    var method = item.shift();
    if (analytics[method]) analytics[method].apply(analytics, item);
}
Run Code Online (Sandbox Code Playgroud)

analytics在那一点上是一个局部变量,在我们完成重放之后,我们用本地替换全局analytics(这是真正的交易).

希望有道理.我们实际上会在我们的博客上有关于第三方Javascript的所有小技巧的系列文章,所以你很快就会挖掘它!