Click here to Skip to main content
15,878,959 members
Articles / Programming Languages / Javascript
Tip/Trick

7 JQuery Best Practices

Rate me:
Please Sign up or sign in to vote.
4.69/5 (25 votes)
14 Apr 2014CPOL4 min read 45.9K   30   10
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:

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

Microsoft CDN is as follows:

HTML
<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:

JavaScript
<script>Window.JQuery || document.write(‘<script src="script/localsourceforjquery">
</script>’)

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:

JavaScript
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.

JavaScript
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:

JavaScript
var $divId = $("#divId")

and then use $divId whenever you need to.

So instead of doing this:

JavaScript
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:

HTML
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:

HTML
$("#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:

HTML
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:

HTML
$("#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:

HTML
$("#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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.m2a.ca
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionit's good overview Pin
m.elqadi4-Jun-15 1:47
professionalm.elqadi4-Jun-15 1:47 
GeneralMy vote of 5 Pin
Santosh K. Tripathi4-Feb-15 21:52
professionalSantosh K. Tripathi4-Feb-15 21:52 
BugCDN FallBack Pin
jtcmedia28-Jul-14 10:48
jtcmedia28-Jul-14 10:48 
GeneralMy vote of 5 Pin
Mr Digs17-Apr-14 4:36
Mr Digs17-Apr-14 4:36 
GeneralMy vote of 3 Pin
X Vinoth Arun Raj15-Apr-14 18:41
X Vinoth Arun Raj15-Apr-14 18:41 
QuestionGood one Pin
Vivek Johari15-Apr-14 7:55
Vivek Johari15-Apr-14 7:55 
Questionmy vote of 5 Pin
Govindaraj Rangaraj14-Apr-14 23:07
Govindaraj Rangaraj14-Apr-14 23:07 
SuggestionNot all is about JQuery, but still good article. Pin
VMAtm14-Apr-14 22:30
VMAtm14-Apr-14 22:30 
GeneralRe: Not all is about JQuery, but still good article. Pin
Mack Ait-Aoudia15-Apr-14 2:36
Mack Ait-Aoudia15-Apr-14 2:36 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun14-Apr-14 19:54
Humayun Kabir Mamun14-Apr-14 19:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.