Reputation: 48402
I have an MVC 5 app. I have the Google Analytics code and the tracking code in a separate .js file as follows:
// Google Analytics code
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', '-------------', 'auto');
ga('send', 'pageview');
// Google Analytics tracking code
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '-------------']);
_gaq.push(['_trackPageview']);
(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);
})();
This .js file is in my BundleConfig.cs file as follows:
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/Misc/googleAnalytics.js",
"~/Scripts/modernizr-*"
));
In my _Layout.cshtml file, I have the BundleConfig file referenced as follows:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<title></title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
Does this look correct? I want to make sure this is working as it's supposed to.
Upvotes: 3
Views: 6385
Reputation: 500
Anywhere in the <head>
is fine, so you're good as far as location goes, however your tracking code is not correct. You're including both the old and the new tracking codes, you should remove the old tracking code and only keep the new one. Remove everything after the line that says
// Google Analytics tracking code
The new (universal) tracking code uses google's javascript file named "analytics.js" the old (classic) one uses the javascript file named "ga.js". So if you ever see ga.js, follow the instructions for upgrade. https://developers.google.com/analytics/devguides/collection/upgrade/guide
Upvotes: 3
Reputation: 8168
from google analytics documentation:
Paste your snippet (unaltered, in it’s entirety) into every web page that you want to track. Paste it immediately before the closing
</head>
tag. If you use templates to dynamically generate pages for your site (like if you use PHP, ASP or a similar technology), you can paste the tracking code snippet into it's own file, then include it in your page header.
so i think it should be the last script in your bundle:
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*",
"~/Scripts/Misc/googleAnalytics.js"
));
Upvotes: 4