Archive for August, 2007

154Part IIIDocument Objects ReferenceObject detection works (Web server hosting) best when

Friday, August 31st, 2007

154Part IIIDocument Objects ReferenceObject detection works best when you know for sure how all browsers implement the object. Inthe case of document.images, the implementation across browsers is identical, so it is a verysafe branching condition. That s not always the case, and you should use this feature with care- ful thought. For example, IE4 introduced a documentobject array called document.all, whichis used very frequently in building references to HTML element objects. NN4, however, did notimplement that array, but instead had a document-level array object called layers, which wasnot implemented in IE4. Unfortunately, many scripters used the existence of these array objectsas determinants for browser version. They set global variables signifying a minimum version ofIE4 if document.allexisted and NN4 if document.layersexisted. This is most dangerousbecause there is no way of knowing if a future version of a browser may adopt the object of theother browser brand or eliminate a language feature. For example, Opera in its native settingsupports the document.allarray. But if you expect that browser to support every detail of theIE4 browser, scripts will break left and right. This is why I recommend object detection not for browser version sniffing but for object avail- ability branching, as shown previously for images. Moreover, it is safest to implement objectdetection only when all major browser brands (and the W3C DOM recommendation) haveadopted the object so that behavior is predictable wherever your page loads in the future. Techniques for object detection include testing for the availability of an object s method. Areference to an object s method returns a value, so such a reference can be used in a condi- tional statement. For example, the following code fragment demonstrates how a function canreceive an argument containing the string ID of an element and convert the string to a validobject reference for three different document object models: function myFunc(elemID) { var obj; if (document.getElementById) { obj = document.getElementById(elemID); } else if (document.all) { obj = document.all(elemID); } else if (document.layers) { obj = document.layers[elemID]; } if (obj) { // statements that work on the object} } With this object detection scheme, it no longer matters which browser brand, operating sys- tem, and version supports a particular way of changing an element ID to an object reference. Whichever of the three documentobject properties or method is supported by the browser(or the first one, if the browser supports more than one), that is the property or methodused to accomplish the conversion. If the browser supports none of them, no further state- ments execute. If your script wants to check for the existence of an object s property or method, you mayalso have to check for the existence of the object beforehand if that object is not part of allbrowers object models. An attempt to reference a property of a non-existent object in a con- ditional expression generates a script error. To avoid the error, you can cascade the condi- tional tests with the help of the &&operator. The following fragment tests for the existence ofboth the document.bodyobject and the document.body.styleproperty: if (document.body && document.body.style) { // statements that work on the body s style property}

Web server logs - 153Chapter 13JavaScript Essentialsoptimized for usage through relatively slow

Friday, August 31st, 2007

153Chapter 13JavaScript Essentialsoptimized for usage through relatively slow network connections and viewing on smallscreens. Numerous other browsers are designed to provide Web accessibility for userswith disabilities through technologies such as speech synthesis and touch screens (seehttp://www.w3.org/WAI). If such browsers do not understand the tag forrefreshing content, they land at this page with no further automatic processing. But bycreating an image that acts as a link, the user will likely click (or tap) on it to continue. The link then leads to the nonscriptable home page. Also note that the altattribute forthe image is supplied. This takes care of Lynx and compact browsers (with image load- ing off) because these browsers show the altattribute text in lieu of the image. Usersclick or tap on the text to navigate to the URL referenced in the link tag. I have a good reason to keep the background of the branching index page plain. For thosewhose browsers automatically lead them to a content-filled home page, the browser windowflashes from a set background color to the browser s default background color before the newhome page and its background color appear. By keeping the initial content to only the com- pany logo, less screen flashing and obvious navigation are visible to the user. One link alternate destinationsAnother filtering technique is available directly from links. With the exceptions of NN2 andIE3, a link can navigate to one destination via a link s onclickevent handler and to anothervia the hrefattribute if the browser is not scriptable. The trick is to include an extra returnfalsestatement in the onclickevent handler. Thisstatement cancels the link action of the hrefattribute. For example, if a nonscriptablebrowser should go to one version of a page at the click of a link and the scriptable browsershould go to another, the link tag is as follows: Product Catalog Only nonscriptable browsers, NN2, and IE3 go to the nonJSCatalog.htmlpage; all others goto the JSCatalog.htmlpage. Object detectionThe final methodology for implementing browser version branching is known as object detec- tion. The principle is simple: If an object type exists in the browser s object model, it is safe toexecute script statements that work with that object. Perhaps the best example of object detection is the way scripts can swap images on a page innewer browsers without tripping up on older browsers that don t implement images as objects. In a typical image swap, onmouseoverand onmouseoutevent handlers (assigned to a link sur- rounding an image, to be backward compatible) invoke functions that change the srcpropertyof the desired image. Each of those functions is invoked for all scriptable browsers, but youwant them to run their statements only when images can be treated as objects. Object models that implement images always include an array of image objects belonging tothe documentobject. The document.imagesarray always exists, even with a length of zerowhen no images are on the page. Therefore, if you wrap the image swapping statementsinside an ifconstruction that lets browsers pass only if the document.imagesarray exists, older browsers simply skip over the statements: function imageSwap(imgName, url) { if (document.images) { document.images[imgName].src = url; } }

152Part IIIDocument Objects ReferenceListing 13-3: A Branching Index (Web hosting support)

Thursday, August 30th, 2007

152Part IIIDocument Objects ReferenceListing 13-3: A Branching Index Page

Go
Notice that the only visible content is an image surrounded by a standard link. The tag contains no background color or art. A single script statement is located in the Head. Atag is also in the Head to automate navigation for some users. To see how a variety ofbrowsers respond to this page, here are what three different classes of browser do withListing 13-3: .A JavaScript-enabled browser.Although the entire page may load momentarily (at most, flashing the company logo for a brief moment), the browser executes the script state- ment that loads home1.htmlinto the window. In the meantime, the image is preloadedinto the browser s memory cache. This image should be reused in home1.htmlso thedownload time isn t wasted on a one-time image. If your pages require a specific browserbrand or minimum version number, this is the place to filter out browsers that don tmeet the criteria (which may include the installation of a particular plug-in). Use theproperties of the navigatorobject (Chapter 38 on the CD-ROM) to write a browser snifferscriptthat allows only those browsers meeting your design minimum to navigate to thescripted home page. All other browsers fall through to the next execution possibility. .A modern browser with JavaScript turned off or missing.Several modern browsersrecognize the special format of the tag as one that loads a URL into the currentwindow after a stated number of seconds. In Listing 13-3, that interval is zero seconds. The tag is executed only if the browser ignores the Where?
If you can read this, JavaScript is not available.
Here s some stuff afterward. Scripting for different browsersA number of solutions exist for accommodating different client browsers because the spe- cific compatibility need might be as simple as letting a link navigate to a scripted page for

Hp web site - 149Chapter 13JavaScript Essentialsthough JavaScript is turned on by

Tuesday, August 28th, 2007

149Chapter 13JavaScript Essentialsthough JavaScript is turned on by default in most browsers, many institutional deploymentsturn it off when the browser is installed on client machines. The reasons behind this MISdeployment decision vary from scares about Java security violations incorrectly associatedwith JavaScript, valid JavaScript security concerns on some browser versions, and the factthat some firewalls try to filter JavaScript lines from incoming HTML streams. All JavaScript-capable browsers include a set of tags to balancethe tag set. If one of these browsers has JavaScript turned off, the



The body of your document.

You can display any standard HTML within the

Web design online - 147Chapter 13JavaScript EssentialsHiding scripts entirely? It may be

Monday, August 27th, 2007

147Chapter 13JavaScript EssentialsHiding scripts entirely? It may be misleading to say that this HTML comment technique hides scripts from olderbrowsers. In truth, the comments hide the scripts from being rendered by the browsers. Thetags and script statements, however, are still downloaded to the browser and appear in thesource code when viewed by the user. A common wish among authors is to truly hide scripts from visitors to a page. Client-sideJavaScript must be downloaded with the page and is, therefore, visible in the source view ofpages. There are, of course, some tricks you can implement that may disguise client-sidescripts from prying eyes. The most easily implemented technique is to let the downloadedpage contain no visible elements, only scripts that assemble the page that the visitor sees. Source code for such a page is simply the HTML for the page. But that page is not interactivebecause no scripting is attached unless it is written as part of the page defeating the goalof hiding scripts. Any scripted solution for disguising scripts is immediately defeatable bythe user turning off scripting temporarily before downloading the page. All of your code isready for source view. If you are worried about other scripters stealing your scripts, your best protection is toinclude a copyright notification in your page s source code. Not only are your scripts visibleto the world, but so, too, are a thief s scripts. This way you can easily see when someone liftsyour scripts verbatim. One other option for minimizing other people borrowing your JavaScript code is to usea JavaScript obfuscator, which is a special application that scrambles your code andmakes it much harder to read and understand. The code still works fine but it is very hardto modify in any way. You would use an obfuscator just before placing your code online, making sure to keep the original version for making changes. One JavaScript obfuscatorthat has been available for several years is a shareware program called JavaScriptScrambler(http://www.quadhead.de/). Script libraries (.js files) If you do a lot of scripting or script a lot of pages for a complex Web application, you will cer- tainly develop some functions and techniques that you can use for several pages. Rather thanduplicate the code in all of those pages (and go through the nightmare of making changes toall copies for new features or bug fixes), you can create reusable script library files and linkthem to your pages. Such an external script file contains nothing but JavaScript code no This kind of tag should go at the top of the document so it loads before any other in-documenttag pair is required, even though nothing appears between them. You can mix Statements inside the tag set execute only upon the firing of the event. No function definitionsare required. This way of binding an object s event to a script means that there is no event handler definedin the element s tag. Therefore, it guarantees that only IE4 or later can carry out the scriptwhen the event occurs. But the tag and attributes contain a lot of source code overhead foreach object s script, so this is not a technique that you should use for script statements thatneed to be called by multiple objects. Also be aware that you cannot use this tag variation if non-IE or pre-IE4 browsers load thepage. In such browsers, script statements execute as the page loads, which certainly causesscript errors. Hiding script statements from older browsersThe number of people using old Web browsers that don t support scripting languages hasdiminished considerably in the past few years. However, new devices, such as mobile phonesand pocket-sized computers, often employ compact browsers that don t have built-inJavaScript interpreters. Nonscriptable browsers do not know about the tag. Therefore, their natural inclination is to render anylines they encounter after the opening JavaScript interpreters know to ignore a line that begins with the HTML beginning commentsequence, but they need a little help with the ending sequence. The close of the HTML com- ment starts with a JavaScript comment sequence (//). This tells JavaScript to ignore the line; but a nonscriptable browser sees the ending HTML symbols and begins rendering the pagewith the next HTML tag or other text in the document. An older browser doesn t know whatthe tag is, so the tag is ignored and rendering begins after that. If you design your pages for public access, it s still a good idea to include these HTML com- ment lines in all your tag set that specifies the scripting language via the typeattribute. You can have any number of such tag sets in your document. For example, you candefine some functions in the Head section to be called by event handlers in HTML tags withinthe Body section. Another tag set can reside within the Body to write part of the content ofthe page as the page loads. Place only script statements and comments between the start andend tags of the tag set. Do not place any HTML tags inside unless they are part of a stringparameter to a document.write()statement that creates content for the page. Every opening The typeattribute is required for the It s important to note that the languageattribute was deprecated in HTML 4, with the typeattribute being the recommended way of specifying the scripting language for