If you are a developer that uses Google Analytics in your ASP.net web applications then you know that loading up the Google Analytics in your web page should not happen when you are building the application. In the past I have always just commented out the section for Google Analytics until publishing the site. Then I would go in and uncomment the lines. This works if you do not forget to uncomment the lines in production. (This happened to me).
I decided that there had to be a better way to automatically do this. After searching the internet and pulling together prior knowledge of how an asp.net web site works I decided to use the web.config to help me. First add the following lines to your web.config production transformation file. (See here if you do not understand the transformation idea).
Note: In your development instance just change the Instance to equal something other than production.
[sourcecode language=”xml”]
<appSettings>
….
<add key=”GoogleAnalytics” value=”UA-111111-11″/>
<add key=”Instance” value=”Prod”/>
….
</appSettings>
[/sourcecode]
With this in place then add the following to each page of the site or to the master page right above the closing body tag
[sourcecode language=”vb”]
<!–Google Analytic Code –>
<% If UCase(ConfigurationManager.AppSettings(“Instance”).ToString()) = “PROD” Then%>
<script type=”text/javascript”>
var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘<% =ConfigurationManager.AppSettings(“GoogleAnalytics”).ToString() %>’]);
_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);
})();
</script>
<% End If %>
</body]
[/sourcecode]
This will not load the Google Analytics until you deploy it to production. Then your web.config will be set to production and will load cleanly.
NOTE: The nice thing about this is you are not limited to Google Analytics conditional load. You can use it for a wide range of things.
Looking for quality web hosting? Look no further than Arvixe Web Hosting!