📜 ⬆️ ⬇️

How to increase the speed of the jQuery script

11 rules, following which you can increase the performance of a script written using jQuery.

Here are the markup based on which there will be examples:

 <div id = "content">
	 <form method = "post" action = "/">
		 <h2> Traffic Light </ h2>
		 <ul id = "traffic_light">
			 <li> <input type = "radio" class = "on" name = "light" value = "red" /> Red </ li>
			 <li> <input type = "radio" class = "off" name = "light" value = "yellow" /> Yellow </ li>
			 <li> <input type = "radio" class = "off" name = "light" value = "green" /> Green </ li>
		 </ ul>
		 <input class = "button" id = "traffic_button" type = "submit" value = "Go" />
	 </ form>
 </ div> 


  1. You need to search for an element by its id attribute. If the element has no id, then you need to specify the element closest to it with id:
    ')
    var active_light = $('#traffic_light .on');

    If we search for an element by id, then this happens quickly, because the getElementById DOM method is used.

  2. Use tag name before class name:

    var active_light = $('#traffic_light input.on');

    Then the DOM method getElementsByTagName is used and the one that has the class 'on' is searched for among the selected elements.
    Sampling elements by class name is one of the slowest samples in jQuery.

    But you should never put the tag name before id:
    var active_light = $('div#traffic_light');

    All elements with the 'div' tag will be selected, and only then an element with the desired id will be found among them.
  3. Cache jQuery objects:
    If you use an object more than once, instead of rotating an element sample several times:
    $('#traffic_light input.on).bind('click', function(){...});
    $('#traffic_light input.on).css('border', '3px dashed yellow');
    $('#traffic_light input.on).css('background-color', 'orange');
    $('#traffic_light input.on).fadeIn('slow');

    save it to a local variable:
    var $active_light = $('#traffic_light input.on');
    $active_light.bind('click', function(){...});
    $active_light.css('border', '3px dashed yellow');
    $active_light.css('background-color', 'orange');
    $active_light.fadeIn('slow');

    '$' before the variable name can be put to show that it contains a jQuery object.

  4. Line up the code in chains:
    Since most jQuery methods return a jQuery object after execution, the previous example can be written like this:
     var $ active_light = $ ('# traffic_light input.on');
     $ active_light.bind ('click', 
      function () {return false;})
    	 .css ('border', '3px dashed yellow')
    	 .css ('background-color', 'orange')
    	 .fadeIn ('slow');
    


    This will allow us to reduce the size of the code.
  5. Use subqueries:
     var $ traffic_light = $ ('# traffic_light'),
    	 $ active_light = $ traffic_light.find ('input.on'),
    	 $ inactive_lights = $ traffic_light.find ('input.off');
    


    Since we saved the object in a variable, the following selections will be made only in the saved object, and not in the entire tree of elements.

  6. Minimize work with the DOM tree
    Since the manipulation (deletion, movement and insertion of new elements) with the DOM tree is rather slow, instead of inserting each element into the DOM:
     var top_100_list = [...], 
     $ mylist = $ ('# mylist'); 
    
     for (var i = 0, l = top_100_list.length; i <l; i ++)
     {
    	 $ mylist.append ('<li>' + top_100_list [i] + '</ li>');
     }
    


    it is better to first create a set of elements in a variable, so that you can insert it into the DOM in one step:
     var top_100_list = [...], 
     $ mylist = $ ('# mylist'), 
     top_100_li = ""; 
    
     for (var i = 0, l = top_100_list.length; i <l; i ++)
     {
    	 top_100_li + = '<li>' + top_100_list [i] + '</ li>';
     }
    
     $ mylist.html (top_100_li);
    

  7. Use event delegation:
    Each event pops up in the DOM tree to ancestor elements. This can be used when multiple elements on the same event need to perform the same function.

    Instead of attaching to each of these elements its own event:
     $ ('# entryform input) .bind (' focus', function () {
    	 $ (this) .addClass ('selected');
     }). bind ('blur', function () {
    	 $ (this) .removeClass ('selected');
     });
    


    You can bind the event to the parent element:
     $ ('# entryform) .bind (' focus', function (e) {
    	 var cell = $ (e.target);  
    
    	 cell.addClass ('selected');
     }). bind ('blur', function (e) {
    	 var cell = $ (e.target);
    	 cell.removeClass ('selected');
     });
    

  8. Link only related scripts to the page.
    Usually, everything comes together in one big script that is inserted on all pages of the site and executed on the $ (document) .ready () event. But even if the function does not work on this particular page, it still takes time to search for the elements to which this function is attached.

    Therefore, you can divide the script into several parts or structure it in the following way:
     var mylib =
     {
    	 article_page:
    	 {
    		 init: function ()
    		 {
    			 ...
    		 }
    	 },
    	 traffic_light:
    	 {
    		 init: function ()
    		 {
    			 ...
    		 }
    	 }
     }
    


    and on the page where we want to use functions related, for example, to traffic_light before the closing </ body> insert:
     <script type = "text / javascript">
         mylib.article.init ();
     </ script>
     </ body>
    

  9. Hold download up to $ (window) .load
    Most often, jQuery developers script execution is tied to the event $ (document) .ready (). The event occurs while the page is being rendered while objects are still loading. Sometimes you can see that the page freezes during loading. The reason for this may be exactly the functions that are bound to $ (document) .ready ().

    To get rid of this, you can bind some of the functions to the $ (window) .load () event, which occurs after all the page content (including the iframe content) has already been loaded.
     $ (window) .load (function () {
    	 // jQuery functions initialized after the page loads
     });
    

  10. Compress js code
    Although it is not and is not related to jQuery.
    This can be done using YUICompressor , Dojo ShrinkSafe , or Google Closure Compiler .
  11. Learn jQuery
    Read the documentation, there you can find a lot of interesting things.
    You can download cheatsheet by jQuery 1.3 , so that the functionality is at the right moments before your eyes.


This is a rather loose translation of this article , which caught my eye. Most of these points I knew and used, but I found some more for myself.

Source: https://habr.com/ru/post/75103/


All Articles