Brian Barthold
Brian Barthold

Reputation: 1623

google analytis in an external js file

I know Google clearly recommends calling analytics inline in the head. However are there any potential pitfalls of calling it in a external file?

I have installed the Google Analytics Debugger for chrome and everything appears normal. I am calling it in an external js file in the head of the page.

Upvotes: 0

Views: 456

Answers (1)

LetterEh
LetterEh

Reputation: 26696

This isn't exactly what Google suggests.

Basically, you can instantiate GA as early as possible -- that's the part that says:

var _gaq = _gaq || [];

The rest of it, you can load at the bottom of the page.

You can even put the _gaq =...; in an external file at the top of the page, and then the rest of it at the bottom.

The goal is this:

Google makes _gaq an array at the beginning. Then you use the array's .push(...); method to add tracking to the array (really, you're just adding arrays of strings).

When you add the second part of the code, at the bottom of the page, it's saving the data that's inside of the _gaq array, to a holding array. Then it's turning _gaq into a real-live program, where .push(...); from now on, on the page, actually sends data and whatnot.

And on initial-load of the full file, _gaq will run through the array of pushed instructions and turn that into a server-call.

They suggest starting _gaq as high on the page as possible, so that you can add user-based tracking to the page, or to buttons, or whatever... ...so that when the program finally does load at the bottom of the page, all of those actions that you've added via _gaq.push(["_method", "data"]); will be tracked by GA, when it's running, so you don't miss any events.

Now, you don't want to put both the _gaq =... part of the code, AND the script-download part of the code at the top of the page. Downloading scripts takes a while. GA is doing it the right way, and is loading it asynchronously, which is perfect... ...but you can still clean it up by moving the second half to the bottom of your page (or putting it in an external script).

So the answer ends up being, yes, feel 100% free to move the GA code into external scripts, that's not going to change a single thing about how it runs.

But you should still consider leaving the external script for _gaq=... at the top (so that if you're tracking user-behaviour to custom events, you can do that as soon as the page is ready -- but then why put that in an external script, when it will take time to load and execute, versus the actually assignment, which will take microseconds, even on slow browsers?).

And then move the script call down the page (or move it into an external file, which is referenced at the bottom of your page).

Upvotes: 2

Related Questions