JavaScript and Jquery Best Practices

|
| By Webner

1. Place Scripts at the Bottom of the Page: If we include script at the top, sometime page elements are not loaded completely and script starts working. So we need to include scripts after loading all the elements. Also if scripts are loaded at the top, browser has to wait for entire JS files to load before displaying the page elements. So this slows down the page load:

//end of the page
<script src="js/folder.js" type="text/javascript"></script>
<script src="js/cabinet.js" type="text/javascript"></script>
</body>
</html>

2. Avoid Globals variable: We need to reduce global variables in the javascript code as they can cause confusion in the code since their value can be modified by any piece of code. Instead of the global variables, we need to use javascript closures and the module pattern. A closure is a function defined inside another function (called the parent function) and has access to variables that are declared and defined in the parent function’s scope. Closure can access its own variables (defined between its curly brackets), can access the outer function’s variables and has access to the global variables.

Closure Example:

function showName (firstName, lastName) {
	var nameIntro = "Your name is ";  
	function makeFullName () {       
	return nameIntro + firstName + " " + lastName;  
	}
	return makeFullName();
} 
showName ("Michael", "Jackson"); // Your name is Michael Jackson

Modules: Javascript Modules are self-contained reusable code. The Module pattern is used to simulate the concept of classes in Javascript so that we can store both public and private methods and variables inside a single object. That allows us to create methods that we want to expose to the world, while still encapsulating private variables and methods in a closure scope.

For Example:

 var monthName = function() {
 var names = ["January", "February", "March", "April","May", "June", "July"];
 return function(number) {
 return names[number];};
}();
console.log(monthName (1)); // January

3. Use Firebug’s ‘debugger’ feature to optimize the code: Firebug is a very good tool in the browser to optimize Javascript and css code. It has features like showing errors, ajax response data from server and css properties being applied for a particular element and more. So we need to use firebug.

Jquery Best Practices:

Selector:

1. Use ID selector whenever possible. It is faster because they are handled using document.getElementById().

2. Use find for child selector. Find() approach is faster:

var $documentId = $("#products div.id"); // bad practice
var $documentId = $("#products").find("div.id");// SLOWER because it has to find the whole DOM for .class
$('.class');
// FASTER because now it only looks under class-container.
$('.class', '#class-container');

3. We need to avoid mixing css with jquery. We can assign a class instead of writing css directly:

$("#mydiv").css({'color':red, 'font-weight':'bold'}); // BAD
$("#mydiv").addClass("error"); // GOOD

Events:

4. Use only one Document Ready handler per page. It makes it easier to debug.

5. We need to avoid anonymous functions to attach events. Anonymous functions are difficult to debug, maintain, test, or reuse:

$("#myId").on("click", function(){   }); // BAD
// GOOD
function showAllElement(){ } // define function here
$("#myId").on("click", showAllElement); //function call

Ajax:

6. Do not put request parameters in the URL while making an ajax call, send them using data object setting:

// Less readable...
$.ajax({
url: "something.php?param1=test1&param2=test2",});
// More readable...
$.ajax({
url: "something.php",
data: { param1: test1, param2: test2 }
});

Use Promise interface: We need to use promises with ajax. Promises are used for managing asynchronous operations. They keep track of when asynchronous operations complete. They overcome issues with multiple callbacks and provide better way to manage success and error conditions.

Normally $.ajax use success and error options for the async callbacks but using promise we need to use done and fail options:

var serverData = $.ajax({  });
serverData.done(successHandler); //.done is the promise.
serverData.fail(failureHandler); 
function successHandler() { 
//function body here  
 }
function failureHandler() {
//function body here 
 }

In success or fail option we cannot pass more than one callback. But Using .done and .fail we can bind any number of callbacks. We can also bind different callbacks based on a result of a condition:

if (condition) {
serverData .done(function(data) {  })
.fail(function(xhr) {    });
  } else {
serverData .done(function(data){    })
.fail(function(xhr) {
    });

Leave a Reply

Your email address will not be published. Required fields are marked *