Testing if a JavaScript Function Exists in IE

Oh IE, how I doth loathe thee…

In an attempt to work around the impending JavaScript breakages that IE8 and InPrivate Browsing will soon bring to many sites around the web 1, a major IE bug-a-boo has been encountered…

So now IE8 users can block ads.  That’s obviously bad for your/your clients’ business, but pretty good for users, right?  Except when functions that are not blocked are dependent on functions that are inside files that are blocked, and thus result in JS breakages…

And thus we come to the reason for this drawn-out email…

At work, we decided to write and implement a small script that checked for the existence of any scripts that cause breakages when missing and create faux functions of the same name, just empty placeholders that will die quietly, to prevent breakages.  Easier said than done…

One might think that this would be a satisfactory test for the existence of the function named ReallyImportantFunction(), right?

if (typeof ReallyImportantFunction == 'undefined'  || ReallyImportantFunction == null) {
   function ReallyImportantFunction(){
      return false;
   };
};

WRONG!!!  Thanks to IE…  Even if the ACTUAL function WAS downloaded and IS present (and thus “defined” and NOT null), IE actually reads inside the above if statement and redefines the original function with the faux function, thus breaking scripts even when IE is NOT blocking the shared JS files…
[insert favorite expletive(s) here]

The long and short of it, you have to redefine like this:

if (typeof ReallyImportantFunction == 'undefined'  || ReallyImportantFunction == null) {
   var ReallyImportantFunction =  function(){
      return false;
   };
};

You have to redefine using the “var XXXX = function()” method, rather than the old-school “function XXXX()” approach…

Thanks to Alex “I can find anything on Google” Khost, and the fine person that tracked this down and wrote an article about it… And, I guess, thanks to IE for giving us all something to write about…

Happy scripting,
Atg


1 For those that do not yet know this, IE8 has a wonderful new “feature” that allows users to block third-party files that they have already downloaded “x-times” on other sites (if the file is not from the site’s same domain). This will of course affect ad script files, but also any files hosted on http://code.google.com/… (hmmm…. which do you think was the real target here??)

Leave a Reply

Your email address will not be published. Required fields are marked *