2013-10-11 78 views
0

我正在寻找类似Google Analytics(分析)JavaScript代码段的工作原理。加载异步JS然后调用函数?

例如,我有这个,

(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'); 

我得到一个没有定义的错误。但是,如果我等待并在控制台中再次调用,则不会再出现错误。我假设脚本还没有完全加载,这就是为什么这个类不存在。

但是它可以调用谷歌分析功能的进口后直接,例如,

(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]'); 

我怎样才能做到这一点与我的脚本?

回答

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');