Best practices for modern Javascript development

by Jean. 44 Comments -

Javascript is definitely a very popular language on the web, and every web developer has to deal with it someday. For this article I have compiled a non-exhaustive list of good practices that will help you to become a better javascript developer.

Use the correct <script> tag

When you have to use some Javascript in an html file, you should always use the following <script> tag:

<script type="text/javascript">
    ... some JS code
</script>

But instead, how many times have you seen this when looking at the source code?

<script type="text/javascript" language="javascript">
    ... some JS code
</script>

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 file

Using 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 <script> tag in your html document to import the file:

<script type='text/javascript' src='http://www.catswhocode.com/myscript.js'></script>

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:

<script language="JavaScript">
<!--
...some code
//-->
</script>

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 framework

Unless 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 var

You 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:

var name = "Jean";
var size = data.length;

Keep your code unobtrusive

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:

<input type="text" name="date" onchange="validateDate()" />

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 files

Not so long ago, it was generally considered good practice to insert your Javascript files within the <head> and </head> 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 <head> and </head> 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:

    <script src="myscript.js?" type="text/javascript"></script>
  </body>
</html>

Use JSLint

JSLint is a web-app which takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate solution.
JSLint is great to find bugs in your code, and also things that may be written in a better way. This site is definitely my favorite coding buddy when developing some Javascript.

Don’t use document.write

The good old document.write method has been deprecated for years, however it is still very common to see it while browsing code.

document.write("hello world");

Instead of using this deprecated method, you should use the DOM and the innerHTML function to insert text on a page:

document.getElementById('hello').innerHTML('hello world');
  • tanmay

    Nice article.

    I still have 1 question about the document.write.
    If you are completely over writing the current document, and not within a specific div/element do we have any other choice, other then using document.write!?

    Thanks,
    Tanmay

    • Frank

      $(‘#wrapper of my website’).after() ?

      • http://webkadabra.com webkadabra

        So much for the JavaScript ^^

  • http://amosrivera.com Amos

    I use html comments to wrap my code so i can have a valid document (http://validator.w3.org/) when i use html tags inside the JS i.e:

    <!–
    element.appendChild("This is an example”)
    //–>

    Althoungh i believe sometimes that is taking validation a bit far i have never had any problems.

    Another nice technique is the use of self executing functions.

    Thanks for the post,

    A.

    • Jeremy

      I do the same

      • http://thetomthorogood.wordpress.com/ Tom Thorogood

        If you’re experiancing validation issues in XHTML you can wrap javascript in // example
        <script type="text/javascript">
        //<![CDATA[
        alert('<b> bold tag');
        //]]>
        </script>

    • Chouch

      That’s why you should read the 2nd point : Use external JS.

      • http://www.stquery.com inspiraller

        Never say ‘never’. Unless you are referring to unfair taxes like: inheritance tax, capital gains tax, stamp duty, vat, parking fees.

        Difference circumstances require inline javascript code. Also, using CDATA instead of comments is not better, it’s just different. Comments are safer and also allow for anything to bet put between them like encoded entities and they support older browsers like ie6, should you need to support it for the company that still lives in the dark ages.

      • Chris

        I understand the point of using external javascript, but if I have one page out of 30 that uses one line of script, there’s not much point to trying to include it with the rest of the main js.

        That being said, I find a handy work-around is to use the jQuery lib and then give my templates a body class depending on the page so that its easier to target with selectors, e.g. $(“.tier2 div#content ul li:first”).html(“some code”);

  • ArminC

    When it comes to inline code, is there a way to do it without jQuery? (I usually use inline JS when I would have to add jQuery just to get rid of a few inline JS, since it would slow down the page and this just seems a bit to trivial to add extra load with jQuery)

    • http://www.wprecipes.com Jean-Baptiste Jung

      Yes, you can :) See http://braksator.com/how-to-make-your-own-jquery for an example.

  • http://poetro.hu/ Peter Galiba

    element.innerHTML is not a function, but a string property, and also not part of any standard, but supported by all major browsers. To set some element’s html use
    document.getElementById(‘hello’).innerHTML = ‘hello world’;

    For more information:
    https://developer.mozilla.org/en/dom:element.innerhtml

  • http://b.enj.am/in Ben

    In regard to point #1:

    With the introduction of HTML5, you can now just use <script> — you don’t need the type=”text/javascript” at all now!

    • http://www.wprecipes.com Jean-Baptiste Jung

      I didn’t knew about this, thanks!

      • http://webkadabra.com webkadabra

        Actually, you can simply use inspite of HTML5. It’s just like that old HTML comments in JS type of thing.

  • http://jonathanmoore.com Jonathan Moore

    Great tips. Another one that I started doing was creating an object for each individual site to maintain scope. That way it helps keep my site variables separate from the frameworks and code I always reuse.

    var MySite = window.MySite || {};
    MySite.test = “hello”;

  • http://blog.shpyo.net shpyo

    Basics, basics, basics. Good that you (again) mentioned about basics.

  • http://gr8code.blogspot.com Julian

    Excelent contribution, I’m currently writing a compendium with good practices when programming with javascript and definitively it will have a reference to this post. thanks

  • http://soygeek.com.mx Isaac

    I read somewhere else that it’s not a good practice to use innerHTML, it’s not a standard, instead you should create a text node then append it to the element, it’s more coding but better practice, I rather use .html() jQuery function :)

    Good tips thanks

  • http://www.cafecomjava.com.br Joel Backschat

    For sure great tips.

  • http://justin-herrera.com Justin

    I’ve always wondered this and maybe you can help. When it comes to including your script tags at the bottom of the html, how do you avoid the flicker effect?

    Take a slider for example. You have multiple images and JS hides them. If you put the scripts at the bottom, then the images will appear and once the JS is done loading all the images disappear and your page jumps (this is bad UX).

    Now you may initially say ‘use CSS to hide the images.’ Yeah, you could do that… but again that can be bad UX and accessibility issues can go with that if the user has JS disabled (it’s something like <5% of users, I can't seem to find the stats tool I used for that…)

    Is there anyway to fix this that's good practice? I tried something on one site which I thought worked pretty well. I loaded a tiny JS file in the head to add CSS rules if JS was enabled. However that goes against the document.write practice above =p

  • http://looking-for-search-for.com Jason

    Excellent tips, yesterday I bought a book about JavaScript development, actually is quick reference and I am going to use it as a combination for Android apps development book.

  • http://www.torquecars.com Brian

    It’s worth noting that some scripts will simply not work at the end of a document, particularly if they are referenced by a form element or other action in the preceding code, it can also cause unpredictable results on pages that load slowly and in other situations. SO TEST TEST TEST is the mantra, and always assume that javascript is turned off – a page should degrade gracefully and still work.

  • http://burielwebwerx.com Hugo

    HTML5, as @Ben pointed out, does not require the ‘type’ attribute as it is set by default if one is not specified. same with , HTML5 defaults to “type=”text/css””:

    URL: http://dev.w3.org/html5/spec/Overview.html#script

    “When used to include dynamic scripts, the scripts may either be embedded inline or may be imported from an external file using the src attribute. If the language is not that described by ‘text/javascript’, then the type attribute must be present, as described below.

    When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, and the src attribute must not be specified.

    The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is ‘text/javascript’.”

    Great post!

  • http://www.yogendrasharma.com Yogendra Sharma

    I have been using JSLint from some time now and it very quality auditor.I prefer using JQuery as much as possible because it is better to use well tested and optimized framework.

    Thanks a lot for pointing all the best practices.

  • http://superdit.com aditia

    I never tried JSLint before, what is the difference between using firebug console?
    And I now I try to always putting event handler outside the html tag

  • http://www.photos2geaux.com/ EJ Domingue

    Yogendra, definitely agree with you I do the same! Also JSLint indeed is a very good auditor. To admin, thanks for the post!

  • http://www.whatbuhttp://www.whatbusinesstodo.com/blogs/savings_society_busines_opportunity Maga Dheera

    Hi! Really useful Info. I changed my opinion after reading this that Java Script playing vital role now a days in HTML designing.

  • Matthew

    You should not use innerHTML either, actually.

    • J. Janz

      That’s right … That’s what DOM is there for: create elements and, if needed, nodeValues … Or, indeed, just use a framework that does this hard work for you … =O

  • http://pcsystemscanner.com Carl

    Most of the times I am using frameworks and IDE like Eclipse, this save me a lot of time and headaches. I am not a good JavaScript developer, the only time I have learned JS is through practice and years of experience with other languages.

  • http://moocr.com/ moocr

    what about “defer” attribute of script tag?

    when the defer attribute set value “defer”, it tell browser this script will not make any html elements and dont show any html elements, please dont care this script at this time, just parse the follow html. is that right?

    • Hugo

      The defer attribute is not supported by all browsers. i think only Firefox and IE understand it. But that could change with the newer browser versions of Opera, Safari, and Chrome.

  • http://jportal.pl shpyo

    Basics are very important!

  • http://www.ghosti.pl ghosti

    Quite good tips for JS beginners.

  • http://fricardo.com/ Flávio Ricardo

    Hi Jean, nice post.

    What about use jQuery instead of $ for more compatibility of jQuery/Javascript code?

    • jon shipman

      That’s only necessary when using multiple frameworks – which no one should ever have to do. Usually for conciseness, in my scripts I use a var $ = jQuery and limit it to a var MyWebsiteScope = function() {}

  • http://iPadflava.com Mike

    I think it’s funny that they say “include scripts at the bottom of your HTML fiiles”, but if you look at their source code, all their scripts are at the top.

  • http://lifedeving.blogspot.com/ Impecy

    Regarding commenting javascript code. What if user will disable executing javascript in his browser. Will he see all pile of code on the pages?

    And thanks for JSLint. I searched something like this for a long time.

    • jon shipman

      No. The browser knows to display:none on the script element. If you’re worried about that, simply include a script{display:none} in your css, though all browsers I know of do this already.

      Users with JS disabled is far below 1%. And I’m sure 99% of that sample are bots that crawl websites.

  • http://www.fromlifetodeath.com Robert Kleffner

    Great post. Thanks for the JSLint, I admit I hadn’t heard of it until now. This’ll probably speed up my development a whole lot.

  • http://lupusmic.org/ Mickaël Wolff

    Script tags must lie in head tag.
    For performance problems: while the page is rendered, external resources are loaded. But, they are fired only when all the main document is loaded. So, it doesn’t matter the JS files lie at the end of the document.
    They are no objective argument to put script tag at the end of the document.
    For performance concerns, it isn’t always a good thing to put CSS and JS files outsite the main document. But I have to say, it isn’t because you inline layout code in your main document it has to be inlined in development files.

  • http://www.stquery.com steve

    I agree with most of the above except the following:
    1) We need document.write in order to have different css load when javascript is not enabled. The way to do this is to
    <head>
    <link rel=”stylesheet” type=”text/css” href=”non_javascript_version.css”/>
    <script type=”text/javascript”>document.write(‘<link rel=”stylesheet” type=”text/css” href=”javascript_version.css”/>’)</script>
    </head>

    2) There is also another benefit in having comments wrapping javascript code, because it makes the page conform to xml format. You can use CDATA instead but this isn’t as forgiving of special characters as comments is.

    • jon shipman

      Valid XML is only relevant when coding for the XHTML doctype. When coding for HTML5 it’s discouraged.