Coding Standards - JavaScript Best Practices - Part 1

JavaScript JQuery
These articles will give you details on best practices for writing JavaScript code.



1. Make JavaScript and CSS external


2. Consider placing JavaScript files at bottom (Delay JavaScript Loading) Putting your scripts at the bottom of the page body, lets the browser load the page first. While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked.


3. Minify JS file

Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced


4. Run JSLint on the JS code to ensure that the code quality is good. It will also point out any JS errors found in the code (such as missing semicolon, etc.)

5. Avoid CSS expressions


6. Avoid fixing any CSS issues using JS



7. Don’t use “var” multiple times, when initializing every variable we tend to use “var” keyword for all the variables



var variableOne = ‘string 1’,
variableTwo = ‘string 2’,
variableThree = ‘string 3’;



8. Minimize DOM access

Accessing the HTML DOM is very slow, compared to other JavaScript statements. If you expect to access a DOM element several times, access it once, and use it as a local variable:Avoid fixing layout with JavaScript


obj = document.getElementById("demo");
obj.innerHTML = "Hello";



9. Minimize fixing styling issues through JS


10. Use camel Case for identifier names (variables and functions)



firstName = "John";
lastName = "Doe";

price = 19.90;
tax = 0.20;

Written by Piece User : pooja@oneact.jp