Tools Blog Learn Quizzes Smile API Log In / Sign Up
Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

5 jQuery performance tips

Difficulty: 30 / 50 Tweet
jquery speed

In today's tutorial I will try to sum up a few things you should take into consideration when writing your jQuery code to avoid performance issues. Some of the following tips will apply to everyone... whether you are a jQuery fan or prefer vanilla flavor.

  1. Don't add elements into the DOM while in a loop. The reason why you shouldn't do this is simple: The DOM is slow! Instead of adding elements one by one with each loop iteration... create a variable containing all that needs to be added and then place it into the DOM. It is even better to not use string concatenation especially in old IE browsers. Replace that with an array and then use the join() function to create the string to be added.

    Bad code:

          
            <script type="text/javascript">
            for(i=0; i<3; i++)
            {
              $('<div></div>').appendTo('body');
            }
            </script>
          
        

    Better code:

          
            <script type="text/javascript">
            var divs = '';
            for(i=0; i<3; i++)
            {
              divs += '<div></div>';
            }
            $(divs).appendTo('body');
            </script>
          
        

    Best code:

          
            <script type="text/javascript">
            var divs = [];
            for(i=0; i<3; i++)
            {
              divs[i] = '<div></div>';
            }
            $(divs.join('')).appendTo('body');
            </script>
          
        
  2. Don't do concurrent Ajax requests. Besides being a poor choice in terms of performance the most important reason why this is a bad practice is because you never know which request is going to reach the server first and therefor can't rely on the returned results. From the examples below you can see that if you really need to make multiple Ajax requests you can wrap that inside a function and then invoke the function again when a request has finished.

    Bad code:

          
            <script type="text/javascript">
            for(i=0; i<3; i++)
            {
              $.ajax({
                url: 'domain.com',
                data: 'something=value'
              }).done(function(r){
                console.log(r);
              });
            }
            </script>
          
        

    Better code:

          
            <script type="text/javascript">
            var i = 0;
            function doAjax()
            {
              $.ajax({
                url: 'domain.com',
                data: 'something=value' + i
              }).done(function(r){
                console.log(r);
                i++;
                doAjax();
              });          
            }
            doAjax();
            </script>
          
        
  3. When possible use CSS transitions instead of jQuery.animate(). The animate() function is much slower than CSS when dealing with animations. Also applying translate3d() on an element triggers the browser to use GPU power to animate it which in turn results in better performance and smoother animations.

    Bad code:

          
            <script type="text/javascript">
            $('.someclass').animate('left', 100, 1000);
            </script>
          
        

    Better code:

          
            <style>
              .someclass { /* transitions and translate3d ... to make use of GPU power*/
                 position: relative;
                 left: 0;
                 -webkit-transition: left 1s linear; -moz-transition: left 1s linear; -ms-transition: left 1s linear; -o-transition: left 1s linear; transition: left 1s linear;
                 -webkit-transform: translate3d(0, 0, 0);
                 -moz-transform: translate3d(0, 0, 0);
                 -ms-transform: translate3d(0, 0, 0);
                 -o-transform: translate3d(0, 0, 0);
                 transform: translate3d(0, 0, 0);
              }
              .someclassmoved { left: 100px; }
            </style>
            <script type="text/javascript">
            $('.someclass').addClass('someclassmoved');
            </script>
          
        
  4. Use id based selectors. Keep in mind that ID based selectors in jQuery use the JavaScript function document.getElementByID() which will return one element instead of an array as it is the case for class based selectors. It is even better to use nested selectors when trying to find elements inside the DOM.

    Bad code:

          
            <script type="text/javascript">
            $('.someclass');
            </script>
          
        

    Better code:

          
            <script type="text/javascript">
            $('#wrapper div.someclass');
            </script>
          
        

    Best code:

          
            <script type="text/javascript">
            $('#wrapper').find('div.someclass');
            </script>
          
        
  5. Don't work with elements inside the DOM. Take them out first using detach() and once you are done playing with them, add them back in using a function like append().

    Bad code:

          
            <div id="table_container">
              <table><tr><td>ID</td><td>Name</td></tr></table>
            </div>
            <script type="text/javascript">
              $('#table_container table').append('<tr><td>1</td><td>John Smith</td></tr>');
            </script>
          
        

    Better code:

          
            <div id="table_container">
              <table><tr><td>ID</td><td>Name</td></tr></table>
            </div>
            <script type="text/javascript">
              var parent = $( "#table_container" );
              var table = parent.find('table');
              table.detach();
              table.append('<tr><td>1</td><td>John Smith</td></tr>');
              parent.append(table);
            </script>
          
        

Hope you liked today's tutorial. If you think of other jQuery performance tips, add your suggestions into the comments section. This can turn into a really comprehensive resource.

comments powered by Disqus