Home >Web Front-end >JS Tutorial >Optimize Jquery and improve web page loading speed_jquery

Optimize Jquery and improve web page loading speed_jquery

WBOY
WBOYOriginal
2016-05-16 17:15:20992browse

Always inherit from the ID selector
Use tag before class
Cache jquery objects
Master powerful chain operations
Use subqueries
For direct DOM operations Limit
Bubbling
Eliminate invalid queries
Delay to $(window).load
Compress js
Comprehensive mastery of jquery library

1. Always inherit from the ID selector

The fastest selector in jquery is the ID selector. Because it comes directly from Javascript's getElementById() method.

Copy code The code is as follows:





  • Red

  • Yellow

  • < ;li> Green





Select the button like this is inefficient:

var traffic_button = $('#content .button');
It is more efficient to directly select the button with ID:

var traffic_button = $('#traffic_button');

Select multiple elements

The mention of multi-element selection is actually talking about DOM traversal and looping, which are relatively slow things. In order to improve performance, it is best to inherit from the nearest ID.

var traffic_lights = $('#traffic_light input');

2. Use tag

before class

The second fastest selector is the tag selector ($('head')). Similarly, because it comes from the native getElementsByTagName() method.

Copy the code The code is as follows:


Traffic Light



  • Red

  • Yellow< /li>
  • Green






Always limit (modify) classes with a tag name (and don’t forget the nearest ID):

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

Note: Class is the slowest selector in jquery. Under IE browser, it will traverse all DOM nodes regardless of where they are used.

Do not modify the ID with tag name. The following example will traverse all div elements to find the node with the id 'content':

var content = $('div#content'); Modifying ID with ID is superfluous:

var traffic_light = $('#content #traffic_light');

3. Cache jquery objects

Develop the habit of caching jquery objects into variables.

Never do this:

Copy the code The code is as follows:

$('# 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');

It is best to cache the object into a variable first and then operate:
Copy the code The code is as follows:

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');

In order to remember that our local variables are packages of jquery, we usually use a $ as a variable prefix. Remember, never let the same selector appear multiple times in your code.

Cache jquery results for later use
If you plan to use jquery result objects in other parts of the program, or your function will be executed multiple times, then cache them in a global variable.

Define a global container to store jquery results, we can reference them in other functions:

Copy the code The code is as follows:

// Define an object in the global scope (for example: window object)
window.$my =
{
// Initialize all queries that may be used more than once
head : $('head'),
traffic_light : $('#traffic_light'),
traffic_button : $('#traffic_button')
};
function do_something()
{
// Now you can reference the stored results and manipulate them
var script = document.createElement('script');
$my.head.append(script);
/ / When you operate inside the function, you can continue to store the query in the global object.
$my.cool_results = $('#some_ul li');
$my.other_results = $('#some_table td');
// Use the global function as an ordinary jquery object.
$my.other_results.css('border-color', 'red');
$my.traffic_light. css('border-color', 'green');
}

4. Master powerful chain operations

The above example can also be written like this:

Copy the codeThe code is as follows:

var $active_light = $('#traffic_light input.on');$active_light.bind('click', function(){…})
.css('border', '3px dashed yellow')
. css('background-color', 'orange')
.fadeIn('slow');

This way we can write less code and make our js more lightweight.

5. Use subquery

jQuery allows us to use additional selector operations on a wrapped object. Because we have saved a parent object in a variable, this greatly improves operations on its child elements:

Copy code The code is as follows:



Traffic Light



  • Red

  • Yellow

  • Green






For example, we can use the subquery method to capture the lights that are on or off, and cache them for subsequent operations.
Copy code The code is as follows:

var $traffic_light = $('#traffic_light'),
$active_light = $traffic_light.find( 'input.on'),
$inactive_lights = $traffic_light.find('input.off');

Tip: You can declare multiple local variables at once using comma separated methods – Save bytes

6. Restrict direct DOM operations

The basic idea here is to build what you actually want in memory, and then update the DOM. This isn't really a jQuery best practice, but is necessary for valid JavaScript manipulation. Direct DOM manipulation is slow.

For example, if you want to dynamically create a set of list elements, never do this:

Copy the code The code is as follows:

var top_100_list = [...], // Assume here are 100 unique strings
$mylist = $('#mylist'); // jQuery selects < ul> Element
for (var i=0, l=top_100_list.length; i{
$mylist.append('
  • ' top_100_list[i] '< /li>');
    }

  • We should create the entire set of element strings before inserting them into the dom:
    Copy the code The code is as follows:

    var top_100_list = [...],
    $mylist = $('#mylist'),
    top_100_li = ""; // This variable will be used to store our list Element
    for (var i=0, l=top_100_list.length; i{
                                                                                                                    ;
    }
    $mylist.html(top_100_li);

    It would be faster if we wrap multiple elements into a single parent node before inserting:
    Copy code The code is as follows:

    var top_100_list = [...],
    $mylist = $(' #mylist'),
    top_100_ul = '
      ';
      for (var i=0, l=top_100_list.length; i{
      top_100_ul = '
    • ' top_100_list[i] '
    • ';
      }
      top_100_ul = '
    '; //Close the unordered list
    $ mylist.replaceWith(top_100_ul);

    If you have done the above and are still worried about performance issues, then:

    Try jquery's clone() method, it will create a copy of the node tree, which allows you to perform DOM operations in an "offline" manner, and then put it back into the node tree when you complete the operation.

    Use DOM DocumentFragments. As the author of jQuery said, its performance is significantly better than direct dom manipulation.

    7. Bubbling

    Except under special circumstances, every js event (for example: click, mouseover, etc.) will bubble up to the parent node. This is useful when we need to call the same function on multiple elements.

    The alternative to this inefficient multi-element event listening is that you only need to bind once to their parent nodes and can calculate which node triggered the event.

    For example, we want to bind this behavior to a form with many input boxes: add a class to the input box when it is selected

    Binding events like this is inefficient:

    Copy code The code is as follows:

    $('#entryform input).bind('focus', function(){
    $(this).addClass('selected');
    }).bind('blur', function(){
    $(this).removeClass('selected');
    });

    We need to listen to the events of getting focus and losing focus at the parent level:
    Copy code The code is as follows:

    $('#entryform').bind('focus', function(e) {
    var cell = $(e.target); // e.target grabs the node that triggered the event.
    cell.addClass('selected');
    }).bind('blur' , function(e){
    var cell = $(e.target);
    cell.removeClass('selected');
    });

    The parent element plays the role of a dispatcher, which can bind events based on the target element. If you find that you have bound the same event listener to many elements, then you must have done something wrong.

    8. Eliminate invalid queries

    Although jquery can handle the situation of no matching elements very elegantly, it still takes time to find. If you only have one global js for the entire site, then it is very likely that all jquery functions will be stuffed into $(document)ready (function(){//All the code you are proud of}).

    Only run functions used in the page. The most effective method is to use inline initialization functions, so that your template can accurately control when and where to execute js.

    For example, in your "Article" page template, you might quote the following code at the end of the body:

    Your global js library may look like this:

    var mylib =
    {
    article_page :
    {
    init : function()
    {
    // Article-specific jQuery function.
    }
    } ,
    traffic_light :
    {
    init : function()
    {
    // Traffic light’s unique jQuery function.
    }
    }
    }

    9. Defer to $(window).load

    Jquery has a very tempting thing for developers. You can hang anything under $(document).ready to pretend to be an event. In most cases you will find this situation.

    Although $(document).rady is indeed very useful, it can be executed when the page is rendered before other elements have been downloaded. If you find that your page is always loading, it is probably $( document).ready function.

    You can reduce the CPU usage when loading the page by binding the jquery function to the $(window).load event. It will be executed after all HTML (including