加载异步JS然后调用函数?

时间:2013-10-11 10:51:13

标签: javascript ajax import

我正在寻找类似于Google Analytics JavaScript代码段工作方式的内容。

例如我有这个,

(function(d, t) {
    var g = d.createElement(t),
        s = d.getElementsByTagName(t)[0];
    g.src = 'myjs.js';
    s.parentNode.insertBefore(g, s);
}(document, 'script')); 

脚本定义了一个类,但是当我调用它时:

var newClass = new myclass('myparam');

我得到一个未定义的错误。但是,如果我等待并在控制台中再次调用它,我将不再收到错误。我假设脚本尚未完全加载,这就是该类不存在的原因。

但是,可以在导入后直接调用Google Analytics功能,例如

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '[userid]', '[website]');

如何使用我的脚本执行此操作?

1 个答案:

答案 0 :(得分:2)

GA代码所做的是使用内联代码立即创建对象。该对象只是在数组中存储调用,直到加载GA脚本。 GA脚本然后使用该数组。 (详见下文。)

你不能用你显示的代码那样做,因为A)它是一个构造函数,而B)你的代码使用了返回值。

以下是GA代码的详细信息:

(function (i, s, o, g, r, a, m) {
    // Remember the name 'ga' on window, using the property GoogleAnalyticsObject
    i['GoogleAnalyticsObject'] = r;

    // Create or retrieve the 'ga' function. If there already is one,
    // it's used as-is. If not, create a new function.
    i[r] = i[r] || function () {
        // The bit in parens initializes an array if there isn't one
        // Then the push call remembers the arguments for this call
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date(); // The bit after the comma sets or updates the `l` property on the function with the timestamp of when this code was run.
    // From here fairly standard, load the GA script asynchronously
    a = s.createElement(o),
    m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');