n00b
n00b

Reputation: 16566

Google Analytics: External .js file

Just to confirm...

file: google.js

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

try {
var pageTracker = _gat._getTracker("UA-11510668-1");
pageTracker._trackPageview();
} catch(err) {}

And then linking the file like:

<script src="google.js" language="javascript" type="text/javascript"></script>

That works, right?

Upvotes: 8

Views: 10458

Answers (4)

Matchu
Matchu

Reputation: 85862

My testing shows that this works.

The sample page provided runs a document.write() in an external script, and then also runs document.write() to print out yet another script tag, to make sure that that functionality works, also. I got expected output (two lines of text) on all browsers I tested, including Internet Explorer (even 6), Firefox, Safari, and Chrome.

I think they just say to do it inline because they think it's easier for newbies.

You should be fine.

Upvotes: 3

Neil Aitken
Neil Aitken

Reputation: 7854

I can't think of a reason it wouldn't.

Have you tried it and encountered any issues?

Edit: I just tried this and inspected it in firebug, as far as I can see, the second script tag is written correctly.

This should work.

Upvotes: 2

hunter
hunter

Reputation: 63562

Add that script to your page, then if you're using FireFox w/ FireBug (or other debugger) or Chrome, you can Inspect Element to see what's been written to the page. If you see...

<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>

...then you should be good to go!

Upvotes: 6

Pawel Pabich
Pawel Pabich

Reputation: 2434

I think you still need to execute that script somehow. If you simply include it then it won't be executed. If you put it inside of a wrapper function:

function googleCode(){
// google code goes here
}

then you can use jQuery and execute it when a page is fully loaded

 $(document).ready(function() {
           googleCode();
        });

Just an idea.

Upvotes: 0

Related Questions