Skip to main content

Client side(Jquery/Javascript/CSS) coding convention and best practices

Type Standard / Convention Example
Linting Use JSHint to detect errors and potential problems.  
Recommended to have nodejs (with npm). Install node-jshint from the command line for automatic linting. node-jshint automatically discovers the closest .jshintrc file and uses it. Or http://jshint.com/ (may produce different results due to absence of jshintrc settings)  
Whitespace This will help to enforce to follow particuler coding convention   
Blank lines separate one block of logically related code from another.  
One space on both sides of binary operators and assignment operators.  
Keywords followed by a "(" (left parenthesis) must be separated by one space.  
There should be no space between the function name and left parenthesis of the argument list. This gives visual distinction between keywords and function invocations.  
Closure Don't use operators as if they are functions (such as delete, void, typeof, new, return, ..).  
Declarations Avoid leakage of variables from or to other modules by wrapping files in a closure. var a, b;
var c = 'c';
var d = 'd';
Line length All variables must be declared before used. JavaScript does not require this, but doing so makes the code easier to read and prevents common mistakes   
Comments Lines should wrap at no more than 80-100 characters. When a statement does not fit on a single line, it may be necessary to span the statement over multiple lines. Place the line break after an operator (ideally after a comma). A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion. The next line should be indented an extra level. // line comments.
 
 /* block comments */
Equality Please be generous with comments in your code, as they help future readers of the code  The below is the result of a long history of browser compatibility, edge cases, performance and other research. Don't take it lightly. There is a reason behind every single detail.
 string: typeof x === "string"
 number: typeof x === "number"
 boolean: typeof x === "boolean"
 null: x === null
 object: x === Object(x)
 Plain Object: jQuery.isPlainObject( x )
 Function: jQuery.isFunction( x )
 Array: jQuery.isArray( x )
 HTMLElement: !!x.nodeType
 undefined: Local variables: x === undefined
 Properties: x.prop === undefined
 Global variables: typeof x === "undefined"

Quotes Strict equality checks (===) should be used in favor of loose (==) wherever possible.  
Naming Single quotes are preferred over double quotes for string literals.  
All variables and functions must use lowerCamelCase for their naming. For functions, verb phrases are preferred (so getFoo() instead of foo()).
 
The only exception to this are constructor functions used with the new operator. These names must start with a capital letter (UpperCamelCase). JavaScript has no dedicated syntax for classes or constructors, they are declared as any other function. As such there is no compile-time or run-time warning for instantiating a regular function or omitting the new operator on a constructor. This naming convention is the only defense we have.
 
Names with acronyms in them should treat the acronym as a normal word and only uppercase the first letter. For example ".getHtmlSource()" as opposed to ".getHTMLSource()".
 
Creating elements   $hello = $( '<div>' )
    .text( 'Hello' );
  To create a plain element, use the simple <tag> syntax in the jQuery constructor:  
Collections When creating elements based on the tag name from a variable (which may contain arbitrary html):
tag = randomTagName(); // will return 'span', 'div' etc.
$who = $( document.createElement( tag ) );
 
Only use $('<a title="valid html" href="#syntax">like this</a>'); when you need to parse HTML (as opposed to creating a plain element).
 
Different types of collections sometimes look similar but have different behaviour and should be treated as such. This confusion is mostly caused by the fact that arrays in javascript look a lot like arrays in other languages, but are in fact just an extension of Object. We use the following conventions:Declaration and
 empty initialisation- $x = $([]);
Access value-y = $x.get( 0 );
 or
 $y = $x.eq( 0 );
Size-$x.length;
Iteration-$x.each( function ( i, element ) {} );
 
Pitfalls Avoid using a for-in loop to iterate over an array (as opposed to a plain object). A for-in will iterate over the keys instead of over the indices:
 keys are strings
 order not guaranteed
 index can have gaps
 might include non-numerical properties
 
Bracket notation on a string ('foobar'[2]) doesn't work in older versions of IE. Use 'foobar'.charAt(2) instead.  
Be careful to preserve compatibility with left-to-right and right-to-left languages (ie. float: right or text-align: left), especially when styling text containers. This is another reason why such declarations should be in CSS files, so that they are automagically flipped by CSSJanus in ResourceLoader for RTL-languages.  
Use attr() and prop() appropriately. Read more at http://javascript.info/tutorial/attributes-and-custom-properties  
Always quote attribute selector values: [foo="bar"] instead of [foo=bar] (jqbug-8229).  
  As of jQuery 1.4 the jQuery constructor has a new feature that allows passing an object as second argument, like jQuery( '<div>', { foo: 'bar', click: function () {}, css: { .. } } );. Don't use this. It makes code harder to follow, fails on attributes (such as 'size') that are also methods, and is unstable due to this mixing of jQuery methods with element attributes. A future jQuery method or plugin or called "title" might convert an element into a heading, which means the title attribute can also no longer be set through this method. Be explicit and call .attr(), .prop(), .on() etc. directly.  
Objects Object declarations can be made on a single line if they are short (remember the line length limits). When an object delcration is too long to fit on one line, there must be one property per line. Property names only need to be quoted if they are reserved words or contain special characters:  var map = { ready: 9, when: 4, "you are": 15 };
Chained Method Calls When a chain of method calls is too long to fit on one line, there must be one call per line, with the first call on a separate line from the object the methods are called on. If the method changes the context, an extra level of indentation must be used.  elements    .addClass( "foo" )    .children()        .html( "hello" )    .end()    .appendTo( "body" );
Global Variables Each project may expose at most one global variable.   
Switch Statements The usage of switch statements is generally discouraged, but can be useful when there are a large number of cases - especially when multiple cases can be handled by the same block, or fall-through logic (the default case) can be leveraged.
 
When using switch statements:
Use a break for each case other than default.
 Align case statements with the switch.
switch ( event.keyCode ) {case $.ui.keyCode.ENTER:case $.ui.keyCode.SPACE:    x();    break;case $.ui.keyCode.ESCAPE:    y();    break;default:    z();}
     
     
CSS    
Whitespace One selector per line .selector,
#some-element {
        float: right;
        text-align: left;
}
 
#look-at-the-left {
        /* @noflip */
        float: left;
        /* @embed */
        background-image: url(images/foobar.png);
}
Opening braces for the CSS rule on the same line as the (last) selector
Indent each declaration with a tab
No space before the colon
1 space between the colon and the value
a semi-colon (;) after each declaration (including the last one)
Closing braces unindented back to the left
Annotation for CSSJanus and CSSMin should be on their own line, above the CSS declaration they're for.
An empty line between one CSS rule and the next.
 
 
 
Quotes In the background-image declaration, the url() syntax is preferred to be used without quotes. They are not needed. The only case where it could cause problems is when an unescaped closing parenthesis occurs in the given path, but those should be URL-escaped.  
  Always put newer versions after older versions   
Naming Name classes and IDs the same way: all lowercase and broken up by dashes.Use the   prefix to avoid conflicts with IDs    

Comments

Popular posts from this blog

Sitecore Site Creation: A Comparison of SXA and Headless SXA

  Objective: Are you thinking about using Sitecore for your website development? If so, you might be wondering whether to use Sitecore Experience Accelerator (SXA) or Headless SXA. In this post, we'll examine the differences between these two methods and help you determine which one is best for your project. Its totally depend on the business context and load model. To design your site using SXA: Sitecore SXA brings Sitecore in competition with other easy to use CMS with enterprise capability. SXA empowers teams to collaborate effectively, streamline website creation, and maintain brand consistency. Its flexibility and scalability make it an excellent choice for enterprise CMS solutions. Few of SXA core enterprise CMS capabilities are: Parallel Work Streams Responsive Grid Layouts Reusable Renderings and Components Themes for Brand Consistency Page Designs for Consistency and Flexibility Customizing Renderings with Variants   But what about Headless SXA? This approach is in hi...

Quickest way to setup Sitecore 10.1 Vanilla instance

Sitecore 10.1 Vanilla installation on Developer machine   Step 1. Install Visual studio 2019 Step 2. Install SQL server 2019 (Developer edition) Step 3. Copy all the setup files and tools at shared location with full rights   Step 4. Browse “Sitecore 10.1.1 rev. 005862 (Setup XP0 Developer Workstation rev. 1.2.3-r6)” folder and run setup.exe in admin mode Step 5. You should be able to see SIA installation screen, click on Start button to start installation Step 6. SIA complete the entire process in 3 parts, first part installed all required Sitecore 10.1 prerequisites. Step 7. Once Prerequisites are installed restart the development machine and open setup.exe again in admin mode (refer step #4). Once SIA will be started then don’t click on Install button again for “Prerequisites”, just click on Skip. Step 8. As I said in Step #6 that Sitecore does installation in three parts, so this is second parts where you will have to pass require parameter to setup sol...

Other aspects of HTML5

There is great feature embedded with HTML5 that is multimedia support without any plugin at end user.The best part of this tag is that it support wide range of quality audio/video format. The tags which we use for audio and video are: <audio> <video> The code snippet for same: <audio id=“audio” controls preload="auto" autobuffer>   <source src="source1.mp3" />   <source src=" source2.ogg" /> </audio> <video id=“video” poster=”poster.jpg" src=”source.mp4" width="2" height="1" x-webkit-airplay="allow” autoplay controls> </video> HTML5 is enriched with other input type tag which is having great ability to enrich the mobile interface,this input type tag along with Jquery UI plugin give them very strong presence on mobile where end user get very lucrative look and feel. <input type="number" pattern="[0-9]*" /> <input type=...