Adding JavaScript to your code dependent upon conditions

Posted by DavidMadden on Geeks with Blogs See other posts from Geeks with Blogs or by DavidMadden
Published on Fri, 06 Apr 2012 06:24:44 GMT Indexed on 2012/04/06 17:31 UTC
Read the original article Hit count: 236

Filed under:

You might be in an environment where you code is source controlled and where you might have build options to different environments.  I recently encountered this where the same code, built on different configurations, would have the website at a different URL.  If you are working with ASP.NET as I am you will have to do something a bit crazy but worth while.  If someone has a more efficient solution please share.

Here is what I came up with to make sure the client side script was placed into the HEAD element for the Google Analytics script.  GA wants to be the last in the HEAD element so if you are doing others in the Page_Load then you should do theirs last.

The settings object below is an instance of a class that holds information I collection.  You could read from different sources depending on where you stored your unique ID for Google Analytics.

*** This has been formatted to fit this screen. ***

if (!IsPostBack)
{
   if (settings.GoogleAnalyticsID != null || settings.GoogleAnalyticsID != string.Empty)
   {
      string str = @"//<!CDATA[ var _gaq = _gaq || []; _gaq.push(['_setAccount', '" 
                       + settings.GoogleAnalyticsID
                       + "']); _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);})();";
      System.Web.UI.HtmlControls.HtmlGenericControl si = 
         new System.Web.UI.HtmlControls.HtmlGenericControl();
      si.TagName = "script";
      si.Attributes.Add("type"@"text/javascript");
      si.InnerHtml = sb.ToString();
   
      this.Page.Header.Controls.Add(si);
   }
}

The code above will prevent the code from executing if it is a PostBack and then if the ID was not able to be read or something caused the settings to be lost by accident.

If you have larger function to declare, you can use a StringBuilder to separate the lines. This is the most compact I wished to go and manage readability.

© Geeks with Blogs or respective owner