4

我正在使用出色的异步脚本加载器 yepnope.js(在 Modernizr2 中)。

我的问题是,将 latset Google Analtics 异步代码合并到 yepnope(如果有的话)的最佳方法是什么?

谷歌建议这个实际的分析代码:

<html>

<head>
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_trackPageview']);
  </script>
</head>

<body>
  <p>Page Content</p>

  <script src="some_random_script.js"></script>

  <p>Page Content</p>

  <script type="text/javascript">  (function() {
    var ga = document.createElement('script');     ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:'   == document.location.protocol ? 'https://ssl'   : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
   </script>
</body>
</html>

但是在 Modernizrs 文档中,他们提到了这一点:

// Give Modernizr.load a string, an object, or an array of strings and objects
Modernizr.load([
  // Presentational polyfills
  {
    // Logical list of things we would normally need
    test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
    // Modernizr.load loads css and javascript by default
    nope : ['presentational-polyfill.js', 'presentational.css']
  },
  // Functional polyfills
  {
    // This just has to be truthy
    test : Modernizr.websockets && window.JSON,
    // socket-io.js and json2.js
    nope : 'functional-polyfills.js',
    // You can also give arrays of resources to load.
    both : [ 'app.js', 'extra.js' ],
    complete : function () {
      // Run this after everything in this group has downloaded
      // and executed, as well everything in all previous groups
      myApp.init();
    }
  },
  // Run your analytics after you've already kicked off all the rest
  // of your app.
  'post-analytics.js'
]);

请注意底线:发布分析。我不想要一个新的 js 文件,因为那是另一个 HTTP 请求。

我应该把它放在 yepnope 之外吗?把它放在 yepnope 框架内有什么好处吗?

阿迪

4

2 回答 2

7

我在Ignited-HTML5-Boilerplate上找到了这个。

<script>
    window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
    Modernizr.load({
        load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
    });
</script>
于 2011-08-22T19:26:11.260 回答
0

不确定这是否是在 yepnope 中合并最新 Google Analytics 代码的“最佳方式”,但在 yepnope 中集成 google 代码的一种方法是:

<script type="text/javascript">
Modernizr.load([
  {
    // WEB ANALYTICS loaded by yepnope (beta)
    test: Boolean(SITEID = ''), // TODO: Fill the site ID to activate analytics
    complete: function() {
        if (SITEID) {
            var _gaq=[['_setAccount',SITEID],['_trackPageview']]; 
            (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
            g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g,s)}(document,'script'));
        }
    }
  }
]);
</script>

将此代码放在标签之前应该</body>没问题。

于 2011-12-06T22:12:00.563 回答