Frontend Best Practices

jQuery Guidelines

General rules

  • don’t mix Javascript with HTML
  • place Javascript files at the bottom of your files so that JS files will be loaded only when the content has been properly displayed
  • load libraries from CDN if possible
  • comment your code as much as possible, but keep it simple

Incorrect:  //Here I am parsing through an array to get the value of the inputs using                           $index from jQuerys' each method

Correct: // Get the information the user enters. 

 

Variables

 

 

  • always use var to declare variables
  • choose easy to understand and short names for variables and functions
Correct:
        isLegalAge();

Incorrect:
        createNewMemberIfHeOrSheIsOverEighteen();
        xyz();
 
  • use camelCase for naming variables
  • avoid global variables as much as possible or try to reduce their number! you run the danger of your code being overwritten by any other JavaScript added to the page after yours
  • variables that are used to store/cache jQuery objects should have a name prefixed with a $
var $myDiv = $(“#my-div”);
$myDiv.hide();


var $this = $(this);

Selectors

 

  • use ID selectors when possible, it’s faster than searching through an undefined number of classes
Correct:
        $(“#main”)       // fast

Incorrect:
        $(“.my-class”)      // slow
        $(“div#main”)       // slow
  • use find() for child nested selectors
Correct:
        $(“#main”).find(“.my-class”)

Incorrect:
        $(“.my-class”)
        $(“#main”).find(“#my-div”)
  • give your selectors a context
Correct:
        $(“.my-class”, “#my-container”)

Incorrect:
        $(“.my-class”)
  • avoid the universal selector
Correct:
        $(“.buttons”).children();

Incorrect
        $(“.buttons > * ”):

DOM Manipulation

 

  • cache elements that need to be used multiple times, it will reduce the time needed to access them each time
Correct:
    var $myDiv = $(“#my-div”);
        $myDiv.addClass(“new”)
              .html(“Hola!”)
              .show();

Incorrect:
        $(“#my-div”).addClass(“new”);
        $(“#my-div”).html(“Hola!”);
        $(“#my-div”).show();
  • chain methods; when the chain grows over 3 links or gets complicated use line breaks and indentation to make it more readable
  • always detach any existing element and attach it back after manipulating it; this way reduce DOM manipulation by removing tha element
var $myList = $(“#container”).find(“ul”).detach();

    $(“#another-container”).append($myList );
  • don't do operations on nonexistent elements
Correct:

var $myElem = $("#no-such-thing");

if( $myElem.length ) {
    $myElem.toggle();
} 

Incorrect:

// NOT OK: probably return undefined and ruin everything!!!
$("#no-such-thing").toggle();
  • use string concatenation or array.join() instead of append() when adding new elements 
Correct:

    var $myList = $("#list"),
        myContent = "";
    for(var i = 0; i < 10000; i++){
        list += "<li>"+i+"</li>";
    }
    $myList.html(myContent);

Incorrect:

    var $myList = $("#list");
    for(var i = 0; i < 10000; i++){
        $myList.append("<li>"+i+"</li>");
    }

MISCELLANEOUS

 

  • use only one Document Ready handler per page; here you can call the functions you previously declared
  • combine jQuery with native JavaScript when needed
#(“#my-div”);   // is still a little slower than...

document.getElementById(“#my-div”);
  • use classes instead of inline styles
Correct:
   $(“#main”).addClass(“fancy”);

    .fancy {
        background-color: gold;
    }

Incorrect:
   $(“#main”).css({“background-color”:”gold”});
  • when using arrays use normal for loops ( for in loops are error prone because it loops over all the present keys in the object and its prototype chain) 
Correct:

        function printArray(arr) {
            var l = arr.length;
            for ( var i = 0; i < l; i++) {
                print(arr[i]);
            }
        }

Incorrect

        function printArray(arr) {
            for ( var key in arr) {
                print(arr[key]);
            }
        }

Done again!

Frontend Best Practices - JS

By adabojor

Frontend Best Practices - JS

Holaaa

  • 289