September 18, 2013

Common String operations

We deal with strings to do just about anything. In this post, I am listing some of the common string operations that one would face every now and then.

September 11, 2013

Dynamically loading JavaScript files

This post is about a situation where one might need to dynamically select and load a javascript file based on a logic. For example, if you have deployed a site but accessing it from multiple domains / sub-domains but you want to load correct analytics code, etc. This might sound silly at the first instance, but reasonable situation are when the same site is deployed to be accessed from multiple countries and they have urls like domain.co.uk and domain.com.au .

So, in this example, I will show how to dynamically load the correct analytics files based on the domain name. At first, there is a function  - CheckUrl() - that checks the url and based on the url calls the LoadAnalytics() function passing the correct script files. One thing to note here is that the analytics script files are saved in separate javascript files.

The LoadAnalytics() function creates a script element, sets the source  property and appends the script element to body section of the page. The CheckUrl() function also needs to be called from the onload event of the page. Here is the source code for the page.

Dynamic JavaScript
  1. function CheckUrl()
  2. {
  3.     var url = window.location.href.toLowerCase();
  4.     var au = ".com.au";
  5.     var uk = ".co.uk"
  6.     if(url.indexOf(au) >= 0)
  7.     {        
  8.         LoadAnalytics("js/au.js");
  9.     }
  10.  
  11.     else if(url.indexOf(uk) >= 0)
  12.     {
  13.         LoadAnalytics("js/uk.js");
  14.     }
  15. }
  16.  
  17.  
  18. function LoadAnalytics(scriptLocation)
  19. {
  20.     var script = document.createElement("script");
  21.     script.type  = "text/javascript";
  22.     script.src   = scriptLocation;
  23.     document.body.appendChild(script);
  24. }


To verify if it is working, you can check the source code but the analytics code will not show up in the page. To verify if it works, place an alert statement in the script file and you will see the alert works. You can also use the Network tab in Page Inspector in Google Chrome to check if the script has loaded.
To verify further, you will need to check if the tracking data comes in your analytics software.

Reference: Shahed Kazi at AspNetify.com