外部Jquery加载 - 第一个OnClick函数一直工作第二个OnClick工作间歇性

时间:2014-09-02 21:48:51

标签: jquery

我从跟踪Google Analytics中的pdf和zip点击的外部js加载以下内容。 pdfOnClick函数一直有效,但zipOnClick间歇性地工作。

(function () {
function loadScript(url, success) {
    var script = document.createElement('script');
    script.src = url;
    var head = document.getElementsByTagName('head')[0],
        done = false;
    script.onload = script.onreadystatechange = function () {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            done = true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
    head.appendChild(script);
}

loadScript('http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',

function () {
    $("a[href$='pdf']").each(function (index) {
        pdfLabel = $(this).attr('href');
        pdfOnClick = "ga('send','event','PDF','downloaded','" + pdfLabel + "');";
        $(this).attr("onClick", pdfOnClick);
    });    

    $("a[href$='zip']").each(function (index) {
        zipLabel = $(this).attr('href');
        zipOnClick = "ga('send','event','ZIP','downloaded','" + zipLabel + "');";
        $(this).attr("onClick", zipOnClick);
    });
});
})();

我创建了一个jsfiddle来查看jshint是否显示任何问题,但它恢复了干净。

我的问题是你看到pdfOnClick函数一直有效的原因,但zipOnClick没有?

http://jsfiddle.net/cbww3zr3/2/

@osowskit你提到没有启用javascript的处理用户。是否最好废弃jquery并将其分配给类似的行为:

<a onclick="ga('send','event','zip','downloaded','label',{'hitCallback': function() {document.location = 'http://example.com/test.zip';}}); return false;" href="http://example.com/test.zip" target=_blank>Click Here</a>   

1 个答案:

答案 0 :(得分:0)

与此Answer类似。

您看到的行为差异是第一个链接打开一个新的页面/选项卡,而第二个链接直接导航到zip。对于第二种情况,GA事件在GA收到事件之前被取消。

您可以打开新的链接/窗口或使用GA hitCallback(请记住处理未启用Javascript的用户)。

当我调试GA事件时,我总是在浏览器的Developer Tools中观察网络流量。在Chrome中,您可以保留页面之间的日志,这将清楚地显示获取(取消)的GA事件。

相关问题