Home > UI/UX Development > JavaScript > 17 Useful jQuery Tricks and Best Practices

17 Useful jQuery Tricks and Best Practices

This post was most recently updated on July 29th, 2024

In the previous article, we learned about Common jQuery Ajax methods and options. In this article, we will cover the some general Do’s and Dont’s or Best Practices in jQuery, which is helpful to increase your page speed and will optimize code.

jQuery is the most popular client-side library. It has many features ( HTML/DOM/CSS manipulation, Traversing, Ajax etc. ) and it easy to learn. This reason makes to the jQuery most popular client-side library. It helps in implementing complex functionality with ease, But too much jQuey and non-optimization jQuery code can decrease your page performance and can result in slow loading.

In this article, I have listed some best techniques which could help you optimize your jQuery.

1. Load jQuery file from CDN
Content Delivery Network’s (CDN) is a system of distributed networks that deliver web page and other web content to the user. Rather than hosting your website on a single server, you can distribute the files/pages and load across multiple systems. Google, Microsoft, Yahoo, and JQuery provide a CDN. CDN load always a cached version and save our server bandwidth, improves a lot your website’s performance.

We recommend load CDN file via HTTPS, even your own websites use HTTP.

Google CDN follows:


jQuery CDN follows:


2. Load jQuery locally When CDN fails
I know above mention CDN’s are awesome but sometimes it may fail to load your hosted file or in offline mode, you need to make sure when that type thing happen your application still runs. So use the fallback.


')
If there is no window.jQuery property defined it means CDN script didn’t load.

3. Always Use the latest Version of jQuery
Each version Of jQuery comes with lots of bug fixes and performance enhancement. jQuery team add some new methods and remove old methods in new releases. It’s good to always add the latest version of jQuery or use the new version of CDN file to get benefits of new changes.

4. Use External file of jQuery
It’s good to place your jQuery code in an external file place of embed JS in HTML page. The external file advantages are It allows caching, More readable code, Ease to manage, Can Host on CDN and minifying the JS. I agree it makes an extra HTTP request to get the js code but the external file has many advantages.

5. Script file in or ?
Scripts tag can be placed in and before the close, both have worked just fine for you. Put library script such as the jQuery library in the head section and other normal files unless it becomes a performance/load issue.

If you include script file in bottom section

It prevents visual delay before the end user sees the actual page because first HTML/CSS parse after that it calls script file
There’s no need to have a check if the DOM is loaded using document.ready since by having the scripts at the end, you know for sure it is.
6. Use Shortcut for Ready Method
A page can’t be manipulated until the document is “ready”. jQuery detects this state of readiness for you. The .ready() method is equivalent to the shorthand method, Shorthand has just less code or somewhat less readable, It didn’t affect your performance but most experienced developers use the shorthand method.

// A $( document ).ready() block. $( document ).ready(function() { console.log( “ready!” ); }); // Shorthand for $( document ).ready() $(function() { console.log( “ready!” ); });

7. DRY ( Do Not Repeat Yourself )
What does it mean Don’t repeat yourself? if you’re repeating yourself, you’re doing it wrong, while writing our code we write the same code for the same action for the multiple time. If you follow the DRY it increases readability, flexibility, cost efficiency, testing, and quality. Overall it is maintainable code and an improved development efficiency.

// BAD if ( eventfade.data( “currently” ) !== “showing” ) { eventfade.stop(); } if ( eventhover.data( “currently” ) !== “showing” ) { eventhover.stop(); } if ( spans.data( “currently” ) !== “showing” ) { spans.stop(); } // GOOD!! var elems = [ eventfade, eventhover, spans ]; $.each( elems, function( i, elem ) { if ( elem.data( “currently” ) !== “showing” ) { elem.stop(); } });

You can use run one event on multiple selectors. It selects the combined results of all the specified selectors.

//BAD $(‘#element1’).click(function(){ hideMe(); }); $(‘#element2’).click(function(){ hideMe(); }); $(‘#element3’).click(function(){ hideMe(); }); //GOOD!! $(“#element1, #element2, #element3”).click(function(){ hideMe(); }); function hideMe(){ $(‘#abc’).hide(); } //BAD $( “div” ).css( “border”, “3px solid red” ); $( “.myClass” ).css( “border”, “3px solid red” ); //GOOD!! $( “div,.myClass” ).css( “border”, “3px solid red” );

You can use .on() to bind a function to multiple events:

//BAD $(‘#element’).on(‘keyup’, function(e) { // e.type is the type of event fired }); $(‘#element’).on(‘keypress’, function(e) { // e.type is the type of event fired }); //GOOD!! $(‘#element’).on(‘keyup keypress’, function(e) { // e.type is the type of event fired });

You can call the same function conditionally. It more readable and manageable.

//Call on load fireOnLoadAndClick(“load”); //Call on click fireOnLoadAndClick(“click”); function fireOnLoadAndClick(eventType){ //Detect the event //Your actoin }

8. Element Checker
Check if an element exists in DOM before manipulating any action. It’s good practice to check the element but not obvious code. I recommend always check the element while using jQuery plugin such as a slider, data table etc. It saves your app from errors.

//BAD This runs three functions before it // realizes there’s nothing in the selection $( “#element” ).slideUp(); // Better: var elem = $( “#element” ); if ( elem.length ) { elem.slideUp(); }

9. Optimize Selectors
jQuery selectors allow you to select and manipulate HTML element(s) quite easily. Some jQuery methods use browser native method.

Avoid the Universal Selector

Always use specific selector instead of a universal selector. It increases the query time.

$( “div > *” ); // Extremely expensive. $( “div .class” ) // Better. $( “:radio” ); // Implied universal selection. $( “*:radio” ); // Same thing, explicit now. $( “input:radio” ); // Much better.

Use ID’s place of Classes

It good to select element by ID place of Classes. jQuery uses the browser’s native method getElementByID() to retrieve the object, resulting in a very fast query and the specificity of ID is more than class.

Increase jQuery Selector Specificity

Beginning your selector with an ID is always best. Calculates the specificity of a given selector using the Specifty Calculator.

$(‘#myId div.myClass’) // Faster $(‘div.myClass’) //Slower

Be specific on the right-hand side of your selector, and less specific on the left.

$( “div.data .gonzalez” ); // Unoptimized: $( “.data td.gonzalez” ); // Optimized:

jQuery Extensions

Avoid use of jQuery extensions because they call the native method querySelectorAll(). Check the Avoid jQuery Extensions Test

// Slower (the zero-based :even selector is a jQuery extension) $( “#myTable tr:even” ); // Better and faster, though not exactly equivalent, It select $( “#myTable tr:nth-child(even)” );

Minimize the number of selectors or Avoid Excessive Specificity

Use the least number of selectors required to style an element. If you run into a conflict, on that time need to increase specificity otherwise don’t add more selectors. It increases the specificity but it decreases the selector speed. Check the Avoid Excessive Specificity Test.

$( “.data table.attendees td.gonzalez” ); // Better: Drop the middle if possible. $( “.data td.gonzalez” );

10. Merge + Minify Script
We can increase the page performance and decrease the load time with merging and minify (compress) the script file.

Merging: Merge all script file into once script file it prevents extra HTTP request and process all script concurrently.

Minification: Compress the script file. Smaller file sizes equal faster load times. There are many compressor tools are available which minify file online, Such as Google Closure Compiler and JavaScript Minifier.

11. Check Plugin Before Including
On the internet, there are thousand of jQuey plugins available which make your job easier. A few point must be informed while adding the plugin. You should ask this question yourself.

Need: Does it really require the plugin to complete functionality? For specific functionality, I don’t recommend adding the plugin which gives extra features apart from our goal. In that scenario, it is good to build that feature own.
File size: Is plugin bigger than source code? If yes mean something wrong.
Performance: Is plugin is impacting your app performance?
Cross Browser Support: check plugin is support major browsers.
Options: Check the options for our future action.
12. Minimize DOM Manipulations
DOM manipulations insert operations like prepend(), append(), after() are time-consuming. Check this article html vs .append vs .innerHTML Performance. innerHTML call bowser native method getElementById(id) so it runs fast.

Use append inside the $.each loop to avoid low performance. Making cache the selector we can save the time of selector DOM traversing and manipulations in long loops. Making string and caching the selector we can optimize our code.

//BAD $.each( listArray, function( i, item ) { var listItem = “

  • Item ” + item + “
  • “; $( “#listItem” ).append( listItem ); }); //BETTER var listItemSelector = $( “#listItem” ); $.each( listArray, function( i, item ) { var listItem = “

  • Item ” + item + “
  • “; listItemSelector.append( listItem ); });

    Another simple technique is to build up a string during each iteration of the loop. After the loop just set the HTML of the DOM element to that string.

    var listItem = “”; var listArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; $.each( listArray, function( i, item ) { listItem += “

  • Item ” + item + “
  • “; }); $( “#listItem” ).html( listItem );

    13. Use jQuery Chain Method
    With jQuery, you can add together actions/methods. jQuery allows us to run multiple methods on the same selector within in single statement. It makes performance better, makes code short and easy to manage. The chain starts from left to right, so left will run first and so on.

    .end() method returns the object to its previous state in the chain.

    //BAD $(“#myDiv”).hide(); $(“#myDiv”).show(1000); $(“#myDiv”).css(“padding-left”, “10px”); //USE CHAIN METHOD //It run from left to right, So it first hide then show and after that it will add padding $(“#myDiv”).hide().show(1000).css(“padding-left”, “10px”);

    Read What is Method Chaining in JavaScript for more detail about jQuery Chain method.

    14. Cache Variable and Selector
    This is most important tips, developers generally ignore to make cache variable or selector. It can improve the performance of jQuery drastically. You should cache jQuery object in the variable if you need to use the same sets of the element in multiple times in DOM. It is manageable and saves selector DOM traversing. Remeber caching can be the cause of memory leaks. So write code smartly. 🙂

    Above example can be cached.

    var myDiv = $(“#myDiv”); //USE CHAIN METHOD myDiv.hide().show(1000).css(“padding-left”, “10px”); $(myDiv).click(function(){ //YOUR ACTION });

    Using Global, Local and Lexical scope you can cache the variable. Read more about JavaScript Scope.

    15. Passing an Attribute Object
    With jQuery, you can set the single attribute as well as multiple attributes for the set of matched element, Using jQuery’s .attr() method to get the value of an element’s attribute has two main benefits: Convenience and Cross-browser consistency.

    The Same thing applies to jQuery style property CSS() and custom .animate() effect method.

    var demoLink = $(‘#demoLink’); demoLink.attr(“href”, “#”).attr(“title”, “Demo Link”).attr(“rel”, “external”); // BAD // GOOD , An object of attribute-value pairs to set. demoLink.attr({href: “#”, title: “Demo Link”, rel: “external” });

    16. Avoid Use of Too Much jQuery
    Having a lot of little scripts can be a performance problem and low maintainability. Don’t add unnecessary scripts to your code which are achievable by using CSS and HTML. CSS3 animations allow animation of most HTML elements without using the script. So try to do less script.

    myDiv.css({‘color’:red, ‘font-weight’:’bold’}); // BAD //GOOD myDiv.addClass(“error”); //BETTER .error { color: red; font-weight: bold; } //BAD demoLink.attr({href: “#”, title: “Demo Link”, rel: “external” }); //GOOD Example Link

    17. Understand jQuery
    jQuery does a lot of tasks that require many lines of JavaScript code to succeed. jQuery has many methods, function, and events for specific action on the element(s). There can be more than one method for one action, So it needs to identify which is best or time-saving and how jQuery works.

    So before doing any code read jQuery API documentation. It will give an idea which method/action/event is suitable for your current conditions.

    Conclusion
    Writing optimizes and efficient code improve the performance of an application. jQuery is awesome but without optimized code, it can result in poor application performance, All above mention tips makes your code manageable, readable and cost efficiency as well as increase your app performance

    Resources:

    jQuery Performance
    jQuery API
    Placing scripts at the bottom of your page
    Where should I put