单击按钮后如何插入Google Analytics?

时间:2015-02-18 17:40:18

标签: javascript google-analytics

我正在尝试在点击按钮后插入Google Analytics代码段,因此将其视为访问。

是否可以不需要重新加载页面?

2 个答案:

答案 0 :(得分:1)

您可以使用Event Tracking,即trackPageView(在David Walsh's site上找到]:

_gaq.push(['_trackPageview', 'url-to-track.html']);

按一下按钮:

var button = document.getElementsByTagName("button")[0];

button.addEventListener("click", function() {
  //Button click event
  alert("Tracking pageview");
  _gaq.push(['_trackPageview', 'url-to-track.html']);
}, false);
<button>Track me!</button>

回应你的评论:

var js = 'document.getElementsByTagName("button")[0].onclick=function(){alert("I\'m loaded!");}';

document.getElementsByTagName("button")[0].onclick = function() {
  var script = document.createElement("script");
  //Uncomment this and put the path for your file
  //script.src = "path/to/script.js";

  //Remove this, this is just for the demo
  script.innerHTML = js;

  document.body.appendChild(script);
  alert("Appended script, click the button again");
};
<button>Load a JS file</button>
<p>Or in this case, a string</p>

答案 1 :(得分:1)

首先将Google Analytics代码保存到变量中。

然后在单击按钮时将其附加到head标记。

ga = "(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', 'UA-XXXXXXXX-X', 'auto');" +
     "ga('send', 'pageview');"

$('a.button').on('click', function() {
  $('head').append('<script>' + ga + '</script>');
});