Click here to Skip to main content
Click here to Skip to main content

7 JQuery Best Practices

, 14 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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

GeneralMy vote of 5 PinprofessionalS. K. Tripathi4-Feb-15 22:52 
BugCDN FallBack Pinmemberjtcmedia28-Jul-14 11:48 
The CDN Fallback as written in this article doesn't work for me.
The browser will parse both the opening and closing script tags as actual script tags regardless of them being in a string.
To fix:
document.write('<' + 'script src="script/localsourceforjquery"></' + 'script>')

GeneralMy vote of 5 PinmemberMr Digs17-Apr-14 5:36 
GeneralMy vote of 3 PinmemberX Vinoth Arun Raj15-Apr-14 19:41 
QuestionGood one PinmemberVivek Johari15-Apr-14 8:55 
Questionmy vote of 5 PinmemberGovindaraj Rangaraj15-Apr-14 0:07 
SuggestionNot all is about JQuery, but still good article. PinmemberVMAtm14-Apr-14 23:30 
GeneralRe: Not all is about JQuery, but still good article. PinmemberMack Ait-Aoudia15-Apr-14 3:36 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun14-Apr-14 20:54 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 14 Apr 2014
Article Copyright 2014 by Mack Ait-Aoudia
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid