jQuery Tips to improve page performance

Views:
36

As a web developer you and I can understand the necessity of optimize website. We know even a five second delay in page load could be reason to loose hundreds of user every day.

So writing good and optimize code which is very important and will help to boost your page speed.

As Developers we prefer jQuery over JavaScript because its easy to use, So here i will share few jquery tips to take care while writing custom codes.

About jQuery

Whenever any application launch its newer version it did work on its performance to implement fast or optimize process, but unlike others jQuery not care about it.

jQuery’s target to create easiest way of DOM accessing, so that even beginners can use jQuery easily. But we should care about the performance and processing time, so that we are able to deliver good and fast application.

By using below tips you can speed up your code performance by upto 50%.

Check if an Element Exists

This tip is not about working or accessing node, this tip is related to validation for DOM elemtns. When we start working on DOM we just start using DOM accessing codes without checking that element is available on DOM or not.

We should very careful while using node accessing codes and ensure the availability of DOM node as we all know JavaScript execute statements line by line if an error occur in any of line JavaScript will stop processing not proceed further.

Example:

<script>
  $(function(){   
    if($("#demo").length > 0){     
      $("#demo").text("element found");   
    }else{     
      console.log("#demo node not found")   
    }
  });
</script>

This best practice is best when we are working on dynamic page or have common js file for multiple page. As if element require by you is not available it will not produce error but a message on your console for reference.

Use of For Instead of Each

jQuery provides its method to iterate the array or DOM nodes called $each. But this method is very expensive, instead of using $each of jquery we should use For loop of JavaScript. In below example you will understand how to change any $each function to For loop.

Example: jQuery $(each)

<!DOCTYPE html>
<html>  
  <head>    
    <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>    
    <link rel="stylesheet" href="style.css" />    
    <script src="script.js"></script>  
  </head>  
<body>    
  <h1>Hello Plunker!</h1>    
  <ul class="test">      
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>    

  <div>List Data: <span id="result"></span></div>

  <script>
  $(function(){        
    var v = $(".test").find("li"),lidata="";        // Example of each of jQuery        
    /*$(v).each(function(){          
      lidata = lidata + $(this).text();        
    });*/        // Example of each using for Loop        
    for(var i=0;i<v.length;i++){          
      lidata = lidata + $(v[i]).text();        
    }        
    $("#result").html(lidata)      
  });    
  </script>
</body>
</html>

In Above you can find use of jQuery each and how we can convert each method into javascript for loop.

But question is why we should do that? jQuery itself use for loop to process your list, So there is no point to use jQuery.

Use IDs Instead of Classes or Specific to DOM element

jquery is very popular because of its simple DOM accessing method. Person who knows the basic of CSS can also use jquery because it use CSS Syntex to access DOM. But this raised the performance issue.

We should prefer to use ID over the classes as much as possible. Reason behind this statement is jQuery use core javascript internally and to access DOM javascript has inbuilt method.

document.getElementById("#test");

but for selecting DOM using class name core JavaScript don’t have direct method. If it’s not possible to use ID then use class name attached with Tag name it will execute faster than simple class calling.

Example:

<script>
// jQuery using class 
$(".test").text("abc")

// jQuery using class with tag
$("div.test").text("abc")
</script>

For more specific selector to optimize accessing please visit to below link: https://learn.jquery.com/performance/optimize-selectors/

Use Join Instead String concat()

<!DOCTYPE html>
<html>
  <head>  
    <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>  
    <link rel="stylesheet" href="style.css" />  
    <script src="script.js"></script>
  </head>
  <body>  
    <h1 id="test"></h1>  
    <script>    
      $(function() {      
        var v = [1, 2, 3, 4, 5], str = "";      
        for (var i = 0; i < v.length; i++) {         
          $("#test").append("<li>" + v[i] + "</li>"); // #2 Example of String Concatination
        }       
      });  
    </script>
  </body>
</html>

In above code we demonstrate two type of string concatenation #1 is denoting the string concatenation and #2 is append method of jQuery. Both will result same but expensive for browser memory. Why?

Why should not use: DOM manipulation is most memory consuming for browser and Method append will call itself on every iteration of loop.

What should we do?

<!DOCTYPE html>
<html>
  <head>  
    <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>  
    <link rel="stylesheet" href="style.css" />  
    <script src="script.js"></script>
  </head>
  <body>  
    <h1 id="test"></h1>  
    <script>    
      $(function() {      
        var v = [1, 2, 3, 4, 5], str = [];      
        for (var i = 0; i < v.length; i++) {        
          str.push("<li>" +v[i] + "</li>");      
        }     
        $("#test").html(str.join(""));    
      });  
    </script>
  </body>
</html>

In above example you will find the DOM manipulation operation reduced to 1 from array length.

join() is inbuilt JavaScript method to concatenate the string array which is much faster then string concatination, So avoid string concatination as much as possible.

jQuery Chain methods

In above Cache element tip we learn how to cache element to speed up command execution. In JavaScript we need to create cached element by our self.

<script>
  var v = document.getElementById("demo");
  v.innerHTML = "Paragraph changed!";
  v.style.color = "#aa0000";
  v.style.background = "green";
  v.style.fontSize = "xx-large";
  v.style.fontWeight = "bold";   
</script>

But after introducing jQuery it just not easy to target the DOM but it also comes with new way of writing code called Chaining Method. Chaining Method helps to write five or more different statements in a single statement, It not only helps to reduce the lines of code but it also ensure the fast execution of statements, Why? Because unlike JavaScript we don\’t need to create variables to cache elements. jQuery chaining method does this internally. Here we will find Chaining method snippet. We can write below script code to replace the above JavaScript snippet.

<script>
  $("#demo").html("Paragraph changed!").css({"color":"#aa0000","background":"green","font-size":"xx-large","font-weight":"bold"});
</script>

jQuery search the element and perform chained command on that cached node.

To get more tips visit to my next post:-

JavaScript Performance Tips Part 2

Comments Your Suggestions