Blog Stats
  • Posts - 14
  • Articles - 0
  • Comments - 6
  • Trackbacks - 0

 

Adding JavaScript to your code dependent upon conditions

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.


Feedback

# re: Adding JavaScript to your code dependent upon conditions

Gravatar Why couldn't you do something like this in your master/head content placeholder instead:

<% if (settings.GoogleAnalyticsID != null || settings.GoogleAnalyticsID != string.Empty) { %>
<script type="text/javascript">
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';
})
</script>
<% } %>

That way you keep the view information in the view, and the code with the code. This seems much cleaner and less cohesive. 4/6/2012 12:19 PM | James Sampson

# re: Adding JavaScript to your code dependent upon conditions

Gravatar We want the function to be present only under certain configurations. There are times when it should not be included. The same source code outputs to different websites that need different UAIDs. 4/6/2012 12:23 PM | David

# re: Adding JavaScript to your code dependent upon conditions

Gravatar But that is why I used your exact code in the view. It still does the same check that you had done, and uses the ID that you have in your settings. It is still dependent on conditions, but it is residing where it should. If your conditions aren't met, that block isn't rendered. 4/6/2012 12:40 PM | James Sampson

Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

 

 

Copyright © DavidMadden