简体   繁体   中英

What is the code to use google analytics in seperate .js file?

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!

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM