Skip to main content

Coding Standards and Best Practices for JavaScript/JQuery

jQuery is an extremely powerful library that provides all the tools necessary to create beautiful interactions and animations in web pages, while empowering the developer to do so in an accessible and degradable manner. Here I'll write some of best practices one should use while working with client side scripting.

·         If you are registering script files through code behind, its good practice  to register all javascript/jquery files on page_init, and if you need to register on the fly scripts from code behind then register those scripts in PreRenderComplete event.

·         Use the jQuery shorthand $ where possible:   

$(function() { ... });
instead of
$(document).ready(
function() { ... });

·         Use a document ready event in place of window onload. The handler for the document ready event must be an anonymous declared in the following form:
    
   $(document).ready(function(){
        //all initialization
   });
   Instead of: 
   $().ready(handler);

·         If you want to use jQuery’s $ variable, wrap your code like this:
    
   (function ($) {
    
// code using $ variable
})(jQuery);
  •  Use tabs to indent your code. Be sure to use liberal spacing in your code. 
// Avoid:
if (msg === "test") {
    foo("abc", "def", { data: 1 });
}
// Correct:
if (msg === "test") {
    foo("abc", "def", {
        data: 1
    });
}
  •   If you want to use global variables within the scope of your code, wrap your code like this:
   (function () {
    
var foo = 'bar';
})();
·         Long comments should use /* ... */. Single line comments should always be on their own line and be above the line they reference. For example:

// We're going to loop here

for (var i = 0; i < 10; i++) { }

·         Strict equality checks (===) should be used in favor of == wherever possible.

·         if/else/for/while/try always have braces and always go on multiple lines.

// Avoid:
if (true)
    test();
// Correct:
if (true) {
    test();
}

·         Don't put statements on the same line as a conditional. For example:
// Avoid:
if ( true ) return;
// Correct:
if ( true ) {
    return;
}

·         Assignments should always have a semicolon after them. Semicolons should always be followed by an endline. Assignments in a declaration should always be on their own line. Declarations that don't have an assignment should be listed together at the start of the declaration.

·         All RegExp operations should be done using .test() and .exec(). "string".match() is no longer used.

·         Avoid Internet Explorer errors
o   Use an object if you need an associative array, not an array. Check here for details
o   Declare all local variables with var before they are used.
o   Remove trailing commas from array and object definitions, i.e.:

var object = { foo: 'test' }
instead of
var object = { foo: 'test', }

·         Use #Id selector wherever possible. It is the fastest. Selectors are ranked by performance as follows:
o   #Id
o   Element
o   .class, :pseudoclass and :custom

The Class and PseudoClass and Custom selectors are slower than ID and Element selectors. The deficiency of their performance can be mitigated by combining them with other selector types, so do this wherever possible.

         Examples
$(".odd"); //Inefficient: scans DOM for all elements with odd class

$("tr.odd");//More efficient: Searches only <tr>s with odd class

$("#MyTable tr.odd");//More efficient: searches descendents of #MyTable

$("#MyTable>tbody>tr.odd"); //Best: searches immediate children
   
·         Avoid using direct CSS style changes using .css()and inbuilt style functions, i.e. .length() or .width(), Instead, declare the styles in a class within a CSS Style Sheet file (not inline within an HTML file), and use .addClass(), .removeClass() or .toggleClass() upon your selected object(s). For example:

$("#oddRow").css({
       "background-color":"gray"
    });

Use instead:
$("#oddRow").addClass("alternateRow");

/*In CSS File:*/
.alternateRow
 {
    background-color:gray;
 }

·         No JavaScript or behavioural markup is to be included in HTML files. For example, the red-highlighted code should not be present in HTML any more:

<input type="button" id="TestButton" onclick="TestClickButton()">

·         Use the shorthand event syntax:

$("#TestButton").click(TestFunc); //use this
$("#TestButton").bind("click", TestFunc); //instead of this

·         There is often a requirement to store/cache a jQuery selection in a holding variable. Where this is the case, you should prefix the variable name with a ‘$’. For example:

var $this = $(this);
var $FormTable = $("#formTable");
$FormTable.addClass("testClass");
$FormTable.append("<tr></tr>");

·         Chaining is one of the signature features of jQuery. Used correctly, it can reduce the amount of code we have to write and the amount of data that is held in memory. The above example could have been written efficiently as a chain like so:        

$("#formTable").addClass("testClass").append("<tr></tr>");

Chaining can be considered as an alternative to:
o   Caching jQuery objects in local variables
o   Performing multiple selections

However for long chains, finding and defining a formatting and indentation strategy can be troublesome. It can be better in these instances to cache your jQuery object in a separate variable.


Comments

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API , now let’s do some comparison of Web API with WCF and web services. Web Service WCF Web API Web services are created as files with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and the class name must end with “Controller”. It is SOAP based service and returns data in XML form. It is also based on SOAP and returns data in XML form. Web API is HTTP based service and by default, it returns data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted within the application or on IIS or using window service. It can be hosted within the application or on IIS. It is no...