Google Analytics - Single Page Site - Click Tracki

2019-02-19 06:59发布

问题:

The site in question is http://getstefan.com

Its a single page portfolio site and I have tried using jQuery to add Google Analytics click tracking to every anchor tag on the site hoping to track where people are clicking. There is a script that adds a unique ID to each anchor on the page, so I set a timeout to make sure and place the Google Analytics click tracking after the id has been assigned. Like so:

jQuery(window).load(function(){
        setTimeout(loadOnClick,8000)
    });

    function loadOnClick() {
        jQuery('a').each(function(){
            jQuery(this).attr("onclick", "_gaq.push(['_trackEvent', 'anchor', 'click', '" + jQuery(this).attr('id') + "']);" );
        });
    }

Which results in building a link like so:

<a href="http://getstefan.com/wp-content/themes/inc v2/downloads/CV-StefanHinck-FR.pdf" id="cv" onclick="_gaq.push(['_trackEvent', 'anchor', 'click', 'cv']);"></a>

Everything looks good. Problem is that when I look at my analytics, the only clicks registered are labeled "untitled"

Anyone know what im doing wrong here?

回答1:

First Your anchors don't have an ID assigned, so the code is doing exactly what it should be reporting 'undefined' as the value for something that doesn't exist. For example

<a class="entry-link" href="http://getstefan.com/portfolio/interior-design-logo/"></a>

Second, don't use the timer.

jQuery(window).load(function(){
        setTimeout(loadOnClick,8000)
    });

should be replaced by

jQuery(document).ready(function(){
        loadOnClick();
    });

so you don't have to wait 8 seconds and can just assign everything when the DOM is ready.



回答2:

Might I suggest a slightly more compact version?

Also, this doesn't refer to the anchor's id, it uses the href, might might be suitable for basic scenarios (i.e., if two links direct the user to the same URL, you won't know what link contributed what number of visits.) If you do add ids to your anchors, just replace .attr('href') with .attr('id').

jQuery(document).ready(function() {
    jQuery('a').click(function() {
        _gaq.push(['_trackEvent', 'anchor', 'click', jQuery(this).attr('href')]);
    });
});  


回答3:

In addition to @Babak Naffas's good post, remember that a _gaq.push call initiates an HTTP request.

If your server is speedy, it's entirely possible that the link the user clicked loads before the Google Analytics call does, in which case nothing's going to get tracked.