views:

23

answers:

1

We want to add google analytics a fairly large .NET web site. The site uses several master pages (4 or 5) and so I was going to just paste the requisite javascript into each master page.

<script type="text/javascript">//<![CDATA[

      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"));
    //]]></script>
<script type="text/javascript">//<![CDATA[

      try {
      var pageTracker = _gat._getTracker("UA-xxxxxx-x");
      pageTracker._trackPageview();
      } catch(err) {}
    //]]></script>

Is there a better way to encapsulate this? Just linking to an external js file would not do the trick due to the <![CDATA. We could also create a static method and dump it into an asp:literal. Is there a more elegant solution?

+1  A: 

The easiest way is to migrate the code into an *.ascx web control. You centralize the code in one place (in case it changes) and you can easily add it to whatever pages you need.

Justin Niessner