Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

7 JQuery Best Practices

0.00/5 (No votes)
14 Apr 2014 1  
7 good practices that cover common scenarios that web developers face everyday

Introduction

With the growing popularity of rich web applications and the users’ high expectations of quick response whenever a link or button is clicked, developers started developing and using JavaScript libraries to get the repetitive work done quickly and effectively. One of those and the most popular one is: JQuery. But with the extensive use of JQuery comes another problem: what are the good and bad practices when using JavaScript libraries?

Background

In this tip, I will give you some of the good practices (at least I think so) I learned using, debugging and reviewing JavaScript code. Actually, I chose 7 of them that I think represent the most common scenarios.

1- CDN with a Fallback

The CDN stands for Content Delivery Network and it’s a server that hosts the library for you. Using CDN will give your application the ability to use the caching and avoid loading the library each time a new user’ request hit your site. Google, Microsoft and JQuery provide a CDN.

As the network is never 100% reliable and the server may go down for many reasons, you need to make sure if that thing happens, your application still runs. So use a fallback, which means if the application cannot find the hosted library, it will fall back and load the local copy.

Google CDN is as follows:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 </script> 

Microsoft CDN is as follows:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
 </script>

Notice that instead of specifying a protocol as http we have //. That is because the CDN servers support http and https. If your site has an SSL certificate, you don’t need to worry about it, it will get the file downloaded.

But as I mentioned previously, you still need a fallback if something goes wrong with the CDN server:

<script>Window.JQuery || document.write(&lsquo;<script src=&rdquo;script/localsourceforjquery&rdquo;>
</script>&rsquo;)

Of course, you could also use a Require to configure that JQuery is required, but I feel it’s hustle for nothing.

2- Limit DOM Interaction

There is a cost when manipulating the DOM tree using JavaScript. And this statement applies to JQuery. So try to limit interaction with the DOM. One example I saw when helping a colleague to speed up displaying of data is the use of selectors in a loop. It’s a killer! Look at the following:

containerDiv = $("#contentDiv");
for(var d =0; d < TotalActions; d++)
{
  containerDiv.append("<div><span class='brilliantRunner'>" + 
  d + "</span></div>");
}

What’s wrong here? At first glance, nothing! And my colleague said this piece of code was working just fine! Of course it did! While TotalActions had 50 items, nothing was noticeable but once it rose to 25000, it slowed down a lot and the reason (I discovered while trying things and Googling the problem) is the DOM interaction inside the loop!

Instead of doing this, I just replaced it with an array (after many unsuccessful tries) and used a push function within the loop. At the end, I made a join with an empty string as separator and got the expected results very smoothly and quickly.

var myContent=[];
for(var d = 0; d < TotalActions; d++)
{
  myContent.push("<div><span class='brilliantRunner'>" + 
  d + "</span></div>");
}
containerDiv.html(myContent.join(""));

3- Caching

The most important and distinctive thing in JQuery is the selectors and the way we find elements in DOM tree. But I saw many times, developers using the same selector many times within a function. For example: $(“#divId”). Even if JQuery can select elements very quickly, it is not necessary to search for the same elements many times. So you could just cache your element as:

var $divId = $("#divId")

and then use $divId whenever you need to.

So instead of doing this:

var thefunction = function()
{
    $("#mydiv").ToggleClass("zclass");
    $("#mydiv").fadeOut(800);
}
 
var thefunction2 = function()
{
    $("#mydiv").addAttr("name");
    $("#mydiv").fadeIn(400);
}

Do this and add the chaining to make it even nicer:

var mydiv =$("#mydiv");
var thefunction = function()
{
  mydiv.ToggleClass("zclass")
       .fadeOut(800);
}
 
var thefunction2 = function()
{
  mydiv.addAttr("name")
       .fadeIn(400);
}

Having said that, you don’t need to cache everything every time. Look at the following:

$("#link").click(function()
{
     $(this).addClass("gored");
}

Here, I used $(this) instead of using again $(“#link”) or even try to cache it. Because the object I am dealing with in this case, is the link itself.

4- Find and Filter

I recently find myself confused when trying to get a set of JQuery objects using Find(). Then I realised that what I was trying to do is achievable by the Filter() function instead. It’s important to understand the difference:

Find: will search for elements starting in the actual selection going down the tree.
 
Filter: will search in the whole JQuery set

5- End()

When chaining things inside a JQuery set, you often want to get back to parent to apply any other interesting stuff or creasy attributes. You are in the second row of a table applying some CSS and want to go back to the table to push further the styling? Use the End function when you finish with the row and you are automatically in the table and go ahead make it stylish!

6- Object Literal

When you apply the same CSS attributes with the chaining, use object literal as in the following:

$("#myimg").attr("src", "thepath")
           .attr("alt", "the alt text");

Becomes as follows and you avoid hitting the DOM element and its setter method multiple times:

$("#myimg").attr({"src": "thepath",
           "alt": "the alt text"
 
}); 

7- Classes are Great

Use CSS classes whenever possible instead of inline CSS. I think you don’t need any example nor further explanation about this one.

Points of Interest

I hope this article will help you to code better your jquery applications.

History

  • 13th April, 2014: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here