Coder Perfect

[duplicate] The best spot to put the Google Analytics code

Problem

Where’s the best place to insert the Google Analytics code in WordPress, header or footer? I prefer footer, because I wanted my site to load faster by reducing the number of scripts in the header, but can it work even if the script is in the footer?

Asked by Marky34

Solution #1

Because the original technique for loading ga.js offered by Google was blocking, they used to propose inserting it directly before the /body> element. However, because the improved async syntax may be safely placed in the head with minimal blocking, the current practice is to place it just before the /head> tag.

In the head, there will be some latency; in the footer, there will be a little reduction in the number of pageviews logged. It’s a compromise. Because ga.js is regularly cached and used by a large number of websites, it is frequently provided from the cache, resulting in near-zero latency.

It’s a personal preference of mine to put it in the head>, but it’s really just a question of taste.

Answered by Yahel

Solution #2

As google says:

Answered by Amr

Solution #3

You can use the following code to have your scripts load after the page has been rendered:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            b();
            c.onload = c.onreadystatechange = null;
            d.removeChild(c)
        }
    };
    d.appendChild(c)
}

//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
    // do stuff after the script has loaded
});

Answered by Sparkup

Solution #4

Yes, the GA code should be placed in the footer anyway, as the page shouldn’t be counted as a page visit until all of the markup has been read.

Answered by citizen conn

Post is based on https://stackoverflow.com/questions/6824095/best-place-to-insert-the-google-analytics-code