Hiding JavaScript from older browsers to prevent browser errors, and browser crashes using Google Analytics JavaScript as an example.
There are several possible approaches, but the only one I trust is object/function detection combined with try and catch:
if(functionName) to determine if the browser supports the function. Please not that function names are case sensitive (e.g. getElementByID is not the same as getElementById)try {} catch {} statement to determine if a built in constant (e.g. undefined) is supported.getElementById() does, so you can use if(getElmenentById) as your check before your try and catch statement.eval() functionThe following example shows how I put the above techniques in place to hide Google Analytics JavaScript from older browsers (crashed Netscape 4.x, threw an error for IE 4.x and 5.x):
01 <script type="text/javascript">
02 //<![CDATA[
03 var b_undefined_keyword_supported = false;
04 if(document.getElementById&&!document.layer) {
05 b_undefined_keyword_supported = true;
06 eval("try { var b_test = undefined; }
catch (err)
{ b_undefined_keyword_supported = false;}");
07 }
08 // google scripts
09 if(b_undefined_keyword_supported) {
10 var gaJsHost = (("https:" ==
document.location.protocol) ? "https://ssl."
: "http://www.");
11 document.write(unescape("%3Cscript src='"
+ gaJsHost + "google-analytics.com/ga.js'
type='text/javascript'%3E%3C/script%3E"));
12 }
13 //]]>
14 </script>
15 <script type="text/javascript">
16 //<![CDATA[
17 if(b_undefined_keyword_supported) {
18 var pageTracker = _gat._getTracker("UA-4725824-1");
19 pageTracker._initData();
20 pageTracker._trackPageview();
21 }
22 //]]>
23 </script>
undefined that isn't supported by older browsersundefined keyword with the known exception of IE 5.xAs part of redeveloping my site I decided to install Google Analytics to gather addtional information about the users accessing my site.
Based on my analysis of the browsers still used on the net I decided to test my site under Netscape 4.x+ and IE 4.x+, and found that the Google scripts crashed Netscape 4.x and caused JavaScript errors in IE 4.x and IE 5.x, so I dug up my old page on using object detection in JavaScript, and updated it to the current page.