Some items you should konw :
- Graceful degradation : ensuring that your web pages still work without JavaScript
- Unobtrusive JavaScript : separating structure from behavior
- Backward compatibility : ensuring that older broswers dont choke on your scirpts
- Performance consideration : making sure that your script is performing at its best
Graceful degradation :
Its always worth remembering that a visitor to your site might be using a browser that doesnt
support JavaScript. Or maybe the user has disabled JavaScript. If you dont consider this possibility,
you could inadvertently stop visitors from using your site.
Unobtrusive JavaScript :
Using an attribute like onclick in the markup is just as inefficient as using the style attribute.
You can attach an event to an element in an external JavaScript file :
element.event = action ...
eg : if you want to attach an event to an element with a unique ID, you can simply use getElementByID :
getElementById(id).event = action
There is just one problem. This code will be executed as soon as the JavaScript file loads.
But there is no guarantee which files will finish loading first. So the document may be incomplete when
the script loads, the model of the document is also incomplete, and methods like getElementByTagName
simply wont work.
You need to execute the code once you're sure the document has finished loading.
Fortunately, the complete loading of a document is an event with a corresponding event handler.
window.onload = prepareLinks ;
function prepareLinks() { ... }
Backward compatibility
If you wrap a method in an if statement, the statement will evaluate to either true or false, depending on
whether the method exists . This is called object detection.
As you saw before, methods are objects, just like almost everything else in JavaScript. It makes it quite esay
to exclude browsers that dont support a specific DOM method.
if( !getElementById || !getElementByTagName ) return false;
Performance consideration
- Minimizing DOM access and markup ( 减少DOM 以及 标记 )
- Assembling and placing scripts ( 合并放置 脚本 ) :
Reducing the number of requests required to load a page is probably the number one thing you can do
to improve the overall load time of your website.
- Minification : this refers to the process of taking your script and "compressing" it by removing the unnecessary bits such as whitspace and comments. Minifed code isnt pretty or human-readable, but it can make a big difference in filse size.
In most cases, you will need to keep two copies : a working copy, in which you can make changes an
commens, and the minified copy, which you serve up on your site. As a standard convention, a good idea it
to include min in the file name of minified files to distinguish them from their nonminified couterparts.
<script src = "sciptes/scriptName.min.js"> </scirpt>