This post introduces best jQuery practices you should follow:
Loading from CDN
Instead of storing jQuery on your server, choose to load it from popular CDNs. It will decrease the page loading time.
Below is the list of popular CDNs which you can find jQuery on:
There are some good practices, not only for jQuery, but also for other CSS, JS libraries when loading them from CDN:
Provide a fallback version in your server if loading from CDN fails
Choosing the compressed version
Placing the script at the bottom of page
Using protocol-relative URL
Leaving http: or https: out of the URL. By doing this, the browser will choose to load the https URL of script if your page is severed under https.
Shorthand for the ready event
Naming jQuery object starting with $
With this naming convention, we can know whether or not a variable is a jQuery object.
Use $this variable at the beginning anonymous functions, for example, inside an each loop:
Someone prefer to use that or self. Don't forget to prefix with $ if it's jQuery object.
Caching jQuery objects
If a jQuery object is used multiple times, caching it will save the performance of script.
Chaining method is one of most powerful features of jQuery. It allows us to call multiple methods at the same time.
"Write less, do more", the jQuery's slogan, is perfectly right in this case
Creating new element
When creating new element, try to use jQuery methods to manipulate the element instead of giving full HTML code.
Don't mix CSS with jQuery
Don't set the CSS styles for element directly. Using CSS class instead.
Using ID selector
To retrieve the element by given ID, jQuery uses native document.getElementById() method which is faster than using Sizzle.
Using ID-based selector
Be specific on the right-hand side of your selector, and less specific on the left.
Avoid the universal selectors
Avoid implied universal selectors
It's recommended to prefix a pseudo-class selectors (beginning with :) with a tag name or other selector. Otherwise, the universal selector (*) is still implied.
Using filtering methods instead of pseudo selectors
When possible, use jQuery filter method instead of pseudo selectors. jQuery then uses querySelectorAll method which is faster than using Sizzle methods.
Don't use JS inline to bind events
Always using jQuery to bind events:
Using custom namespace for events
By using custom namespace, you can easily unbind the exact event without affecting to other event handlers which are bound to the element.
Don't put all parameters in Ajax URL
When sending data to remote URL using an Ajax request, use data option to send them instead of putting in the URL.
In the case the parameter might be too long (the article's content, for example), consider to use the POST method for both Ajax requests and the back-end.
Internet Explorer 8 (and earlier) limits
2083 characters in URL