jQuery tips

Posted on by By Nikhilesh, in Front End | 0

We often write traditional code by not knowing limitations and performance issues. In this post, I’m going to discuss few concepts of jQuery with which you can increase performance of those methods.

It is always preferable not to interact with the DOM more frequently. This reduces the performance. For example:

var divs = "";
for (var i = 0; i < total; i += 1) {
    divs += "<div>" + i + "</div>";
}

$("#someId").html(divs);

Consider that there are 10000 records and you are calling the DOM selector every time when something new is appended. By calling so, you are absolutely decreasing the performance of your code. Instead, we can do that as coded above. In the above code what we are doing is, we first render all the records and in the end we are attaching those records to the DOM selector just once in the end. This increases the performance of the code. Alternatively, we can also achieve this using array. For example:

var divs = [];
for (var i = 0; i < total; i += 1) {
    divs.push("<div>" + i + "</div>");
}

$("#someId").html(divs.join(""));

Secondly, many times we get confused when to use find() method and when to use filter() method. SO let’s get into it.

Always remember that find() method looks for descendants or children and this method is useful to find child type of access. Let’s take an example:

<ul class="people">
    <li class="publisher">jQuery</li>
    <li class="publisher">O'Reilly</li>
    <li class="owner">Tim O'Reilly</li>
</ul>
var $names = $(".people li");
var $pubs = $names.find(".publisher");

In the above example, we won’t get any output because there are no child elements for li. Instead, using filter() method gives appropriate result. Hence the code:

var $names = $(".people li");
var $pubs = $names.filter(".publisher");

That’s all for now. In the coming posts, we go ahead with few more tips and tricks on both jQuery and JavaScript.

-By
Uma Maheswar
Helical It Solution

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments