Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Conditional Compilation example- try catch statement

In the beginning of the tutorial, I mentioned how conditional compilation got a boast to its profile when it started showing up in some Ajax related JavaScripts. I'll show you what I mean here. A Ajax script usually contains a central function for testing support for the objects needed to make asynchronous requests in IE and Firefox:

Typical ajax function:

function HttpRequest(url, parameters){
var pageRequest = false //variable to hold ajax object
   if (window.XMLHttpRequest) // if Mozilla, Safari etc
      pageRequest = new XMLHttpRequest()
   else if (window.ActiveXObject){ // if IE
      try {
      pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
      } 
      catch (e){
         try{
         pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
         }
         catch (e){}
      }
   }
   else
   return false
}

Most people think the "try/catch" statements will gracefully test for Ajax support, though unfortunately that's not true. Browsers that do not support "throw/catch", such as IE4.x, will in fact choke on the above code and return an error. To overcome this, conditional compilation can be used to create a truly cross browser friendly Ajax processing function:

Truly cross browser ajax function:

function HttpRequest(url, parameters){
var pageRequest = false //variable to hold ajax object
/*@cc_on
   @if (@_jscript_version >= 5)
      try {
      pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
      }
      catch (e){
         try {
         pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
         }
         catch (e2){
         pageRequest = false
         }
      }
   @end
@*/

if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
}

Using conditional compilation, the entire try/catch block is only rendered by IE5+, sparing browsers like IE4 or non IE browsers from trying to dicipher it. Firefox obviously will pick up on and use XMLHttpRequest instead. And there you have it- a truly cross browser ajax function!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.