|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Scripting Best PracticesAs you start to develop more complex scripts, it's important to know some scripting best practices. These are guidelines for using JavaScript that more experienced programmers have learned the hard way. Here are a few of the benefits of following these best practices:
Whether you're writing an entire AJAX web application or simply enhancing a page with a three-line script, it's useful to know some of the concepts that are regularly considered by those who write complex scripts for a living. The following sections introduce some of these best practices. Content, Presentation, and BehaviorWhen you create a web page, or especially an entire site or application, you're dealing with three key areas: content, presentation, and behavior.
It's a good idea to keep these three areas in mind, especially as you create larger sites. Ideally, you want to keep content, presentation, and behavior separated as much as possible. One good way to do this is to create an external CSS file for the presentation and an external JavaScript file for the behavior, and link them to the HTML document. Keeping things separated like this makes it easier to maintain a large siteif you need to change the color of the headings, for example, you can make a quick edit to the CSS file without having to look through all of the HTML markup to find the right place to edit. It also makes it easy for you to reuse the same CSS and JavaScript on multiple pages of a site. Last, but not least, this will encourage you to use each language where its strengths lie, making your job easier. Progressive EnhancementOne of the old buzzwords of web design was graceful degradation. The idea was that you could build a site that used all of the bells and whistles of the latest browsers, as long as it would "gracefully degrade" to work on older browsers. This mostly meant testing on a few older browsers and hoping it worked, and there was always the possibility of problems in browsers that didn't support the latest features. Ironically, you might expect browsers that lack the latest features to be older, less popular ones, but some of the biggest problems are with brand-new browsersthose included with mobile phones and other new devices, all of which are primitive compared to the latest browsers running on computers. One new approach to web design that addresses this problem is known as progressive enhancement. The idea is to keep the HTML documents as simple as possible, so they'll definitely work in even the most primitive browsers. After you've tested that and made sure the basic functionality is there, you can add features that make the site easier to use or better looking for those with new browsers. If you add these features unobtrusively, they have little chance of preventing the site from working in its primitive HTML form. Here are some guidelines for progressive enhancement:
By the Way The term progressive enhancement first appeared in a presentation and article on this topic by Steve Champeon. The original article, along with many more web design articles, is available on his company's website at http://hesketh.com/. Adding Event HandlersIn Hour 9, you learned that there is more than one way to set up an event handler. The simplest way is to add them directly to an HTML tag. For example, this <body> tag has an event handler that calls a function called Startup. <body onLoad="Startup();"> This method still works, but it does mean putting JavaScript code in the HTML page, which means you haven't fully separated content and behavior. To keep things entirely separate, you can set up the event handler in the JavaScript file instead, using syntax like this: window.onload=Startup; Right now, this is usually the best way to set up events: It keeps JavaScript out of the HTML file, and it works in all browsers since Netscape 4 and Internet Explorer 4. However, it does have one problem: You can't attach more than one event to the same element of a page. For example, you can't have two different onLoad event handlers that both execute when the page loads. When you're the only one writing scripts, this is no big dealyou can combine the two into one function. But when you're trying to use two or three third-party scripts on a page, and all of them want to add an onLoad event handler to the body, you have a problem. The W3C Event ModelTo solve this problem and standardize event handling, the W3C created an event model as part of the DOM level 2 standard. This uses a method, addEventListener(), to attach a handler to any event on any element. For example, the following uses the W3C model to set up the same onLoad event handler as the previous examples: window.addEventListener('load', Startup, false);The first parameter of addEventListener() is the event name without the on prefixload, click, mouseover, and so on. The second parameter specifies the function to handle the event, and the third is an advanced flag that indicates how multiple events should be handled. (false works for most purposes.) Any number of functions can be attached to an event in this way. Because one event handler doesn't replace another, you use a separate function, removeEventListener(), which uses the same parameters: window.removeEventListener('load', Startup, false);The problem with the W3C model is that Internet Explorer (as of versions 6 and 7) doesn't support it. Instead, it supports a proprietary method, attachEvent(), which does much the same thing. Here's the Startup event handler defined Microsoft-style: window.attachEvent('onload', Startup);The attachEvent() method has two parameters. The first is the event, with the on prefixonload, onclick, onmouseover, and so on. The second is the function that will handle the event. Internet Explorer also supports a detachEvent() method with the same parameters for removing an event handler. Attaching Events the Cross-Browser WayAs you can see, attaching events in this new way is complex and will require different code for different browsers. In most cases, you're better off using the traditional method to attach events, and that method is used in most of this book's examples. However, if you really need to support multiple event handlers, you can use some if statements to use either the W3C method or Microsoft's method. For example, the following code adds the ClickMe() function as an event for the element with the id attribute btn: obj = document.getElementById("btn');
if (obj.addEventListener) {
obj.addEventListener('click',ClickMe,false);
} else if (obj.attachEvent) {
obj.attachEvent('onclick',ClickMe);
} else {
obj.onclick=ClickMe;
}
This checks for the addEventListener() method, and uses it if it's found. Otherwise, it checks for the attachEvent() method, and uses that. If neither is found, it uses the traditional method to attach the event handler. This technique is called feature sensing and is explained in detail later this hour. Many universal functions are available to compensate for the lack of a consistent way to attach events. If you are using a third-party library, there's a good chance it includes an event function that can simplify this process for you. Did you Know? The Yahoo! UI Library includes an event-handling function that can attach events in any browser, attach the same event handler to many objects at once, and other nice features. See http://developer.yahoo.net/yui/ for details, and see Hour 8, "Using Built-in Functions and Libraries," for information about using third-party libraries. Web Standards: Avoid Being Browser SpecificThe Web was built on standards, such as the HTML standard developed by the W3C. Now there are a lot of standards involved with JavaScriptCSS, the W3C DOM, and the ECMAScript standard that defines JavaScript's syntax. Right now, both Microsoft and the Mozilla Project are improving their browsers' support for web standards, but there are always going to be some browser-specific, nonstandard features, and some parts of the newest standards won't be consistently supported between browsers. Although it's perfectly fine to test your code in multiple browsers and do whatever it takes to get it working, it's a good idea to follow the standards rather than browser-specific techniques when you can. This ensures that your code will work on future browsers that improve their standards support, whereas browser-specific features might disappear in new versions. By the Way One reason to make sure you follow standards is that your pages can be better interpreted by search engines, which often helps your site get search traffic. Separating content, presentation, and behavior is also good for search engines because they can focus on the HTML content of your site without having to skip over JavaScript or CSS. Documenting Your CodeAs you create more complex scripts, don't forget to include comments in your code to document what it does, especially when some of the code seems confusing or is difficult to get working. It's also a good idea to document all of the data structures and variables, and function arguments used in a larger script. Comments are a good way to organize code, and will help you work on the script in the future. If you're doing this for a living, you'll definitely need to use comments so that others can work on your code as easily as you can. UsabilityWhile you're adding cool features to your site, don't forget about usabilitymaking things as easy, logical, and convenient as possible for users of your site. Although there are many books and websites devoted to usability information, a bit of common sense goes a long way. For example, suppose you use a drop-down list as the only way to navigate between pages of your site. This is a common use for JavaScript, and it works well, but is it usable? Try comparing it to a simple set of links across the top of a page.
Remember to consider the user's point of view whenever you add JavaScript to a site, and be sure you're making the site easier to useor at least not harder to use. Also make sure the site is easy to use even without JavaScript. Design PatternsIf you learn more about usability, you'll undoubtedly see design patterns mentioned. This is a computer science term meaning "an optimal solution to a common problem." In web development, design patterns are ways of designing and implementing part of a site that webmasters run into over and over. For example, if you have a site that displays multiple pages of data, you'll have "Next Page" and "Previous Page" links, and perhaps numeric links for each page. This is a common design patterna problem many web designers have had to solve, and one with a generally agreed-upon solution. Other common web design patterns include a login form, a search engine, or a list of navigation links for a site. Of course, you can be completely original and make a search engine, a shopping cart, or a login form that looks nothing like any other, but unless you have a way of making them even easier to use, you're better off following the pattern, and giving your users an experience that matches their expectations. Although you can find some common design patterns just by browsing sites similar to yours and noticing how they solved particular problems, there are also sites that specialize in documenting these patterns, and they're a good place to start if you need ideas on how to make your site work. Did you Know? The Yahoo! Developer Network documents a variety of design patterns used on their network of sites, many of which are implemented using JavaScript: http://developer.yahoo.net/ypatterns/. AccessibilityOne final aspect of usability to consider is accessibilitymaking your site as accessible as possible for all users, including the disabled. For example, blind users might use a text-reading program to read your site, which will ignore images and most scripts. More than just good manners, accessibility is mandated by law in some countries. The subject of accessibility is complex, but you can get most of the way there by following the philosophy of progressive enhancement: Keep the HTML as simple as possible, keep JavaScript and CSS separate, and make JavaScript an enhancement rather than a requirement for using your site. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |