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

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

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

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...