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 was performing at it best
Graceful Degradation: Its worth remembering, visitor to your site might is using a browser that Doesntsupport JavaScript. Or Maybe the user has disabled JavaScript. If you dont consider this possibility,you could inadvertently the stop visitors from using your site.
unobtrusive JavaScript: Using the attribute like OnClick in the markup is just as inefficient as Using the style attribute. You can attach a event to a 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 = A Ction There is just one problem. This code would be executed as soon as the JavaScript file loads. But there is no guarantee which files would finish loading first. So the document could be incomplete when the script loads, the model of the document was also incomplete, and methods like GE telementbytagnamesimply wont work.
You need to execute the code once your ' re sure the document has finished loading. Fortunately, the complete loading of a document are an event with a corresponding event handler. Window.onload = Preparelinks; function Preparelinks () {...}
Backward CompatibilityIf you wrap a method in an if statement, the statement would evaluate to either true or false, depending on whether the Met Hod exists. This is called object detection. As you saw before, methods is objects, just like almost everything else in JavaScript. It makes it quite esayto exclude browsers a dont support a specific DOM method. if (!getelementbyid | |!getelementbytagname) return FALSE;
Performance Consideration
- Minimizing DOM access and markup (reduce DOM and markup)
- Assembling and placing scripts (merge placement script):
Reducing the number of requests required to load a page are probably the number one thing you can do to improve the OV Erall 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'll need to keep, 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 T Heir Nonminified Couterparts. <script src = "sciptes/scriptname.min.js" > </scirpt>
Best practices in JavaScript