14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3 ■ From DHTML to <strong>DOM</strong> <strong>Scripting</strong><br />

A lot of older scripts use this information to determine whether a browser is capable of supporting their functionality:<br />

<br />

if(navigator.appName.indexOf('Internet Explorer')!=-1 && browserVersion.indexOf('6')!=-1)<br />

{<br />

document.write('This is MSIE! 6');<br />

}<br />

else<br />

{<br />

document.write('This isn\'t MSIE');<br />

}<br />

<br />

This appears rather clever at first glance, but it is not a bulletproof method of finding out which browser is in use.<br />

For example, suppose you display the results of navigator.appName like this:<br />

<br />

if(navigator.appName.indexOf('Internet Explorer')!=-1 && browserVersion.indexOf('6')!=-1)<br />

{<br />

document.write('This is MSIE! 6');<br />

document.write('navigator.appName');<br />

}<br />

else<br />

{<br />

document.write('This isn\'t MSIE');<br />

document.write(''+navigator.appName+'');<br />

}<br />

<br />

The results will show that in Chrome, Safari, <strong>and</strong> Firefox the appName is displayed as “Netscape”, a browser that<br />

has not been developed since 2007. It only gets worse from here. Looking for navigator.userAgent will give you more<br />

mixed results. For example, IE shows up as “Mozilla/4.0 (compatible, MSIE 7.0)” for IE 10 on Windows 7.<br />

Reading out the browser name <strong>and</strong> version—commonly known as browser sniffing—is not advisable, not<br />

only because of the inconsistencies I just pointed out, but also because it makes your script dependent on a certain<br />

browser rather than supporting any user agent that is actually capable of supporting the script.<br />

The solution to this problem is called object detection, <strong>and</strong> it basically means that we determine whether a user<br />

agent supports a certain object <strong>and</strong> makes this our key differentiator. In really old scripts, like the first image rollovers,<br />

you might have seen something like this:<br />

<br />

// preloading images<br />

if(document.images)<br />

{<br />

// Images are supported<br />

var home=new Image();<br />

home.src='home.gif';<br />

var aboutus=new Image();<br />

aboutus.src='home.gif';<br />

}<br />

<br />

www.it-ebooks.info<br />

53

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!