Nikko
Nikko

Reputation: 1286

Is it possible to put Google Analytics code in an external JS file?

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-XXXXXXX-1");
    pageTracker._trackPageview();
}
catch(err) {}

Would it be possible to call this script from an external JS file? I wanted to to something like:

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

and put one of these on each of my HTML pages.
The code I have above will be inside googleanalytics.js
Google's instructions was to put the code in each page. The problem with that is it makes it harder to change the tracking code. (We use different tracking codes for our DEV and PROD pages).
I've tried it out and it doesn't seem to be working.
Is there something wrong with doing that? Or is there something else causing the problem?

Important FYI Please note that we are using IE6 and 8 browsers (yes, I know, no need to tell me)

Upvotes: 32

Views: 33598

Answers (9)

WilliamLong
WilliamLong

Reputation: 1

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX-X';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXX-X');

Upvotes: -1

Keinan Goichman
Keinan Goichman

Reputation: 121

Upload google analytics dynamically:

function loadGoogleAnalytics(){
    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; 
    ga.async = true;
    ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-XX';

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
}

loadGoogleAnalytics(); //Create the script  

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-XXXXXX-XX');

Don't forget to replace XXXXXX-XX with your account id.

Upvotes: 1

Ramanpreet Singh
Ramanpreet Singh

Reputation: 51

i got an easy way to do this... Since analytic js is asynchronous it won't give any problem...

include below code in any js file (Please Note: The code i used is new analytics code provided by google analytics)

var imported = document.createElement('script');
imported.src = 'https://www.googletagmanager.com/gtag/js?id=UA-12xxxxxxx-1';
document.head.appendChild(imported);


window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-12xxxxxxx-1');

Upvotes: 6

Carmela
Carmela

Reputation: 687

@Nikko

One possible reason is because the GA account was created using the old analytics. So you must use the traditional analytics code ga.js (_gaq.push). I found an incompatibility in using the new analytics.js with the traditional GA account in the GA website. The hits won't appear so I was forced to use the traditional ga.js.

Also, you may set a callback function to assure the hits are successfully sent, like below:

//traditional way
_gaq.push(['_set', 'hitCallback', function() {
  console.log("%c ga.js finished sending pageview data to analytics %s ", "color:black; background: pink", pageviewUrl);
}]);

//new analytics way
ga('send', 'pageview', {
            'page': pageviewUrl,
            'hitCallback': function() {
                console.log("%c analytics.js done sending data. pageview url = %s ", "color: black, background: pink", pageviewUrl);
            }
        });

where pageviewUrl = the url of the site

Hope that helps!

Upvotes: 0

Mattis Kopstad
Mattis Kopstad

Reputation: 21

This will work if you divide the script into 2 scripts the same way Google Analytics has divided the traditional script into 2 script tags.

Upvotes: 2

Airn5475
Airn5475

Reputation: 2492

I came across this post while trying to resolve a similiar issue. After searching further I came across another post that worked for me:

Using Google Analytics asynchronous code from external JS file

I had to move the var _gaq outside of the function it was in so that it became global.

Hope this helps!

Upvotes: 3

Jason
Jason

Reputation: 17956

Yes this is possible. If it is not working then there is something else going on.

Just a thought, Google Analytics is usually about a day behind in reporting so when you make changes it will take some time before you know it is working. What I like to do is hit a page that does not get traffic very often to assure me that I have my tracking set up correctly.

Also, you might try making the link an absolute link in your <script tag. It might just be looking in the wrong place for the analytics code.

Upvotes: 17

Draemon
Draemon

Reputation: 34711

Can you not use your server-side language to output the code at the bottom of each page? Have a function such as output_ga() and call that. That way you can change it in one place.

Upvotes: 4

usoban
usoban

Reputation: 5478

Wrap google code into function and execute on each page ;)

Upvotes: 0

Related Questions