1

I read somewhere that placing google analytics tracking code in seperate file is not recommended but I have no idea how to use it for my website (there are .php files and .tpl files and if I tried to put it almost everywhere and there was an error or it didn`t track the visitors).

Could anyone tell me which code I should put into separate .js file and in .tpl file so at least the basic functions would work? Thanks a lot!

3 Answers 3

1

This is the cleanest (using a anonymous auto-executing function):

(function() {
    var _gaq = window._gaq = window._gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
    _gaq.push(['_trackPageview']);

    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

Then reference in either your head or before end of body via:

<script type="text/javascript" src="YOUR_GA_CODE_LOCATION.js"></script>
Sign up to request clarification or add additional context in comments.

Comments

0

you can write google analytics code in separate js file and include that js and call its function -

Suppose, following code is written in mygoogle.js

function loadMyGoogle()
window._gaq = window._gaq || [];
    window._gaq.push([ '_setAccount',
            'setaccounthere']);
(function() {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl'
                : 'http://www')
                + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();
}

then in your php files in header -

<head>
<include script="mygoogle.js">
</head>

In onload function of body tag -

function onload(){
loadMyGoogle();
}

I hope you know how you can set onload event in body tag

Comments

0

Do not put GA code in .js file instead include html page.

Steps: 1) Open notepad and paste GA code there. 2) Save it as HTML page 3) Include that html before end of head tag

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.