Analytics + Facebook跟踪与document.getElementsByTagName('script')[0]的Javascript问题

时间:2013-03-07 05:24:35

标签: javascript facebook e-commerce analytics

我试图通过将Facebook的跟踪代码放在与Analytics相同的页面上来了解代码是否存在冲突,因为这一行出现在两个脚本中:

document.getElementsByTagName('script')[0]

以下是相关代码:

<head>
  <link rel="stylesheet" type="text/css" href="stylesheet.css">

  <!---- START OF FACEBOOK TRACKING SCRIPT  -->
  <script type="text/javascript">
    var fb_param = {};
    fb_param.pixel_id = '6008770441xxx';
    fb_param.value = '123.00';
    (function(){
      var fpw = document.createElement('script');
      fpw.async = true;
      fpw.src = '//connect.facebook.net/en_US/fp.js';

这一行:

      var ref = document.getElementsByTagName('script')[0];
      ref.parentNode.insertBefore(fpw, ref);
    })();
   </script>
   <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/offsite_event.php?id=600877044xxx&amp;value=0" /></noscript>

  <!---- START OF ANALYTICS TRACKING SCRIPT  -->
   <script type="text/javascript">
     var _gaq = _gaq || [];
     _gaq.push(['_setAccount', 'UA-2725xxx-3']);
     _gaq.push(['_trackPageview']);
     _gaq.push(['_addTrans',
       '456',       // order ID - required
       'xxx', // affiliation or store name
       '123', // total - required
       '',    // tax
       '10',  // shipping
       ',     // city
       '',    // state or province
       'Australia' // country
     ]);      
  _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers

  (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>
</head>

1 个答案:

答案 0 :(得分:2)

请参阅该行之后的下一行

var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(ga, s);

现在,这将在First CHild Place中插入元素,谁是第一个将成为第二个,

所以这只是在运行时插入脚本,根本不会发生冲突

:)