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

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.


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');

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.