Click here to Skip to main content
15,172,351 members
Articles / Programming Languages / Javascript
Posted 14 Apr 2014

Tagged as


30 bookmarked

7 JQuery Best Practices

Rate me:
Please Sign up or sign in to vote.
4.69/5 (25 votes)
14 Apr 2014CPOL4 min read
7 good practices that cover common scenarios that web developers face everyday


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?


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="//">

Microsoft CDN is as follows:

<script src="//">

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(‘<script src="script/localsourceforjquery">

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>");

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()
var thefunction2 = function()

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

var mydiv =$("#mydiv");
var thefunction = function()
var thefunction2 = function()

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


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.


  • 13th April, 2014: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mack Ait-Aoudia
Software Developer (Senior)
Canada Canada
No Biography provided

Comments and Discussions

Questionit's good overview Pin
m.elqadi4-Jun-15 2:47
professionalm.elqadi4-Jun-15 2:47 
GeneralMy vote of 5 Pin
Santosh K. Tripathi4-Feb-15 22:52
professionalSantosh K. Tripathi4-Feb-15 22:52 
BugCDN FallBack Pin
jtcmedia28-Jul-14 11:48
Memberjtcmedia28-Jul-14 11:48 
GeneralMy vote of 5 Pin
Mr Digs17-Apr-14 5:36
MemberMr Digs17-Apr-14 5:36 
GeneralMy vote of 3 Pin
X Vinoth Arun Raj15-Apr-14 19:41
MemberX Vinoth Arun Raj15-Apr-14 19:41 
QuestionGood one Pin
Vivek Johari15-Apr-14 8:55
MemberVivek Johari15-Apr-14 8:55 
Questionmy vote of 5 Pin
Govindaraj Rangaraj15-Apr-14 0:07
MemberGovindaraj Rangaraj15-Apr-14 0:07 
SuggestionNot all is about JQuery, but still good article. Pin
VMAtm14-Apr-14 23:30
MemberVMAtm14-Apr-14 23:30 
GeneralRe: Not all is about JQuery, but still good article. Pin
Mack Ait-Aoudia15-Apr-14 3:36
MemberMack Ait-Aoudia15-Apr-14 3:36 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun14-Apr-14 20:54
MemberHumayun Kabir Mamun14-Apr-14 20: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.