But instead, how many times have you seen this when looking at the source code?
In HTML, the language attribute is deprecated due to its redundancy with the type attribute. You should never use it anymore.
Keep your code in an external fileUsing an external .js file for your Javascript code is a lot cleaner than writing it in your html document, and it also allows the browser to cache the file, which will result in a faster website.
Put your Javascript code in a .js file, then use the Don’t wrap code in HTML comments
In the 90's some very old browsers weren’t able to interpret Javascript. In order to prevent unwanted results on those browsers, it was considered good practice in 1994-1997 to wrap Javascript code within html comments, so browsers with no Javascript support will simply ignore it.
Here is an example of some code wrapped within html comments:
However, in 2010, all browsers (Even IE6, that means a lot) can interpret Javascript, so there’s absolutely no need to wrap code within comments anymore. Even worse, if code is wrapped within comments and use the decrement symbol --, you’ll expect some weird problems due to the fact the browser may think it’s the end of the html comment.
Use a frameworkUnless your Javascript code is really short and easy, you should always avoid reinventing the wheel by using a framework of your choice. In my opinion, jQuery is the best and has an awesome community, so you should give it a try if you haven’t already.
Always declare your variables using varYou should introduce any variable you create with the var statement, otherwise it gets to the global scope. Also, using var makes your code more readable and self-explanatory.
Example of variable created using the var statement:
Some years ago, when a programmer wanted to add an event to an html element (for example, if you want to validate a date when the user typed something) he simply put Javascript code in the html, using a special attribute such as onblur, onchange, onclick, etc.
Example:
This works great, but it is a bit dirty. HTML should only contain the document description. Just like it’s bad practice to use inline CSS styles, it’s bad practice to use inline Javascript.
Instead, what about using some unobtrusive Javascript? Using jQuery, it is pretty easy to do, as you can see in the following example:
$(document).ready(function(){$('input[name=date]').bind('change', validateDate);});Include your scripts at the bottom of your HTML filesNot so long ago, it was generally considered good practice to insert your Javascript files within the
and tags of your html document.But browsers read html files from top to bottom, and load external files dynamically. Which mean that inserting scripts within the and tags will make your Javascript load before some of the page content.
In order to always load scripts after the content, Javascript files should always been included at the bottom of your html files, as shown below: