10

Dynamic Tracking Script

A while back I wrote an extension to insert the GoogleAnalytics tracking code.  This worked out great because I added the ability to detect HTTP vs HTTPS and also avoid JavaScript errors if the initial GoogleAnalytics doesn't load.  The problem with the current version was that I placed the Extension content in the Head section of the page.

I say it is a problem because loading the GoogleAnalytics tracking code in the header has two problems: First, the load time on your page can be delayed while the tracking code is loading.  Placing the tracking code in the bottom will allow most everything else to load before it reaches out to Google.  Second, you only want to count page loads that actually complete.  By placing the tracking code at the end of the page you can avoid having your Google Analytics statistics being skewed by incomplete page loads.

A little digging in the Google site gave me the final answer on where to add the tracking code.  So why did I originally place the tracking code in the header?  When I started the extension I looked for a way to add the code to the footer of the page.  BlogEngine includes a section in the settings page called Tracking Script that allows you to manually enter code to be placed in the footer of the page.  That's great of you are configuring this manually but I needed to do it dynamically.  Unfortunately I couldn't locate examples of how to do this sort of magic.

Well finally someone came to my rescue.  Thanks to Morten I have finally been given the means to dynamically add code to the bottom of the pages instead of only in the header section.  The code looks like this:

page.ClientScript.RegisterStartupScript(page.GetType(), "googleAnalyticsScripts", trackerScript.ToString(), false);

Armed with this new information I have updated my GoogleAnalytics extension with this code.  So now the script looks something like the following:

System.Web.UI.Page page = (System.Web.UI.Page)context.CurrentHandler;

StringBuilder trackerScript = new StringBuilder();
trackerScript.AppendLine("");
trackerScript.AppendLine("<!-- Google Tracking Script v1.4 | Chris Blankenship @ www.dscoduc.com -->");
...
trackerScript.AppendLine("<!-- End Google Tracking Script -->");

page.ClientScript.RegisterStartupScript(page.GetType(), "googleAnalyticsScripts", trackerScript.ToString(), false); 
context.Items["GoogleTracker"] = 1;

So if you find yourself in need of dynamically adding content into the Tracking Script section of BlogEngine you now know how to accomplish this task.  And don't forget to get the latest version of the GoogleAnalytics extension!

Add comment


 

biuquote
  • Comment
  • Preview
Loading



Credits

  • DSCODUC on Technorati
  • SpamPoison
  • Project Honey Pot
  • CCA Share Alike 3.0
  • 1and1 Hosting