简体   繁体   English

为了使它们都能正常运行,我必须在哪里放置Google Analytics(分析)代码和Event Tracking(事件跟踪)代码?

[英]Where do I have to put Google Analytics code and Event Tracking code, in order for them both to work correctly?

1) My Google Analytics tracking code is placed in the HEAD, the Event tracking code is placed BEFORE BODY END TAG. 1)我的Google Analytics(分析)跟踪代码放置在HEAD中,事件跟踪代码放置在BODY END TAG之前。

In this version, the clicks are tracked correctly, but the link leads to an /undefined page. 在此版本中,点击被正确跟踪,但是链接指向一个/ undefined页面。

2) When I put both scripts in the HEAD, the links work, but no events are tracked. 2)当我将两个脚本都放在HEAD中时,链接有效,但是没有跟踪任何事件。

QUESTION) What is the correct way to implement both codes? 问题)实现这两个代码的正确方法是什么?

INFO) This is my Google Analytics tracking code INFO)这是我的Google Analytics(分析)跟踪代码

<script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_setDomainName', 'xxxx.xx']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>

This is my Google Event tracking code 这是我的Google事件跟踪代码

<script>
$( '#lp-pom-image-xxx' ).click( function(event) {

event.preventDefault();
var buttonLink = $(this).attr("href");

var callbackFunction = function(){
window.location = buttonLink;
}

if(window._gat){
_gaq.push(['_set','hitCallback',callbackFunction]);
_gaq.push(['_trackEvent', 'x', 'y', 'z']);
} else {
callbackFunction(); 
}
});
</script>

Don't know why the first one is not working. 不知道为什么第一个不起作用。

The second one is not working because your script is not inside a dom ready handler, so when your event registration code is executed the target elements are not loaded in the dom, this results in the handlers not getting added to the target elements. 第二个不起作用,因为您的脚本不在dom准备就绪的处理程序内,因此当执行事件注册代码时,目标元素未加载到dom中,这导致处理程序未添加到目标元素。

So add the script in a dom ready handler 因此,将脚本添加到dom准备就绪的处理程序中

jQuery(function ($) {
    $('#lp-pom-image-xxx').click(function (event) {

        event.preventDefault();
        var buttonLink = $(this).attr("href");

        var callbackFunction = function () {
            window.location = buttonLink;
        }

        if (window._gat) {
            _gaq.push(['_set', 'hitCallback', callbackFunction]);
            _gaq.push(['_trackEvent', 'x', 'y', 'z']);
        } else {
            callbackFunction();
        }
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM