Optimize Jquery to speed up page loading

  • 2020-03-29 23:44:09
  • OfStack

Always inherit from the ID selector
Use tag before class
Cache jquery objects
Master powerful chain operations
Using subqueries
Restrict direct DOM manipulation
The bubbling
Eliminate invalid queries
Postponed to $(window). The load
Compression js
Comprehensive knowledge 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.

<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>
<input class="button" id="traffic_button" type="submit" value="Go" />

Selecting buttons like this is inefficient:

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

Var traffic_button = $(' # traffic_button ');

Select multiple elements

When we talk about multi-element selection, we're really talking about DOM traversal and loops, which are slow things, and to improve performance, it's best to start with the nearest ID.

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

2. Use tag before class

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

<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>
<input class="button" id="traffic_button" type="submit" value="Go" />

Always restrict class 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. In Internet explorer it traverses all DOM nodes regardless of where it is used.

Do not use tag name to decorate the ID. The following example will go through all the div elements to find which node with the ID 'content' :

Var content = $(div # 'content'); Modifying an ID with an ID is also gilding the lily:

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

3. Cache jquery objects

Get in the habit of caching jquery objects into variables.

Never do this:

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

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

To remember that our local variables are wrapped in jquery, we usually prefix them with a $. Remember, never let the same selector appear multiple times in your code.

Cache jquery results, standby
If you plan to use jquery result objects in other parts of the program, or if your function will execute multiple times, cache them in a global variable.

Define a global container to hold jquery results so we can reference them in other functions:

//Define an object at the global scope (for example, the window object)
window.$my =
//Initializes 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 refer to the stored results and manipulate them
var script = document.createElement('script');
//When you are 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 a normal 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:

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

This allows us to write less code and make our js more lightweight.

5. Use subqueries

JQuery allows us to use additional selector operations on a wrapped object, because we've already saved a parent object in a variable, which greatly improves operations on its children:
The same code at the page code block index 1
For example, we can use a subquery method to grab lights that are bright or not and cache them for later action.

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

Tip: you can save bytes by declaring multiple local variables at once using comma-separated methods

6. Limit direct DOM manipulation

The basic idea here is to create in memory what you really want and then update the DOM. This is not a jQuery best practice, but you must do effective JavaScript operations. Direct DOM manipulation is slow.

For example, if you want to dynamically create a list of elements, don't:

var top_100_list = [...], //So let's say I have 100 unique strings here
$mylist = $('#mylist'); //JQuery to <Ul> The element
for (var i=0, l=top_100_list.length; i<l; i++)
       $mylist.append('<li>' + top_100_list[i] + '</li>');

We should create the entire set of element strings before inserting them into the dom:

var top_100_list = [...],
$mylist = $('#mylist'),
top_100_li = ""; //This variable will be used to store our list elements
for (var i=0, l=top_100_list.length; i<l; i++)
        top_100_li += '<li>' + top_100_list[i] + '</li>';

It is faster to wrap multiple elements into a single parent node before we insert:

var top_100_list = [...],
$mylist = $('#mylist'),
top_100_ul = '<ul id="#mylist">';
for (var i=0, l=top_100_list.length; i<l; i++)
     top_100_ul += '<li>' + top_100_list[i] + '</li>';
top_100_ul += '</ul>'; //Unordered list closing

If you are still worried about performance problems after doing the above, then:

Try jquery's clone() method, which creates a copy of the tree of nodes. It allows dom manipulation to take place "offline" and then drop it back into the tree when you're done.

Use DOM DocumentFragments. As the jQuery authors say, its performance is significantly better than direct DOM manipulation.

7. The bubbling

Except in special cases, every js event (click, mouseover, etc.) bubbles to the parent node. This is useful when we need to call the same function on multiple elements.

Instead of this inefficient multi-element event listening, you only need to bind to their parent node once and figure out which node triggered the event.

For example, we want to bind to a form that has many input fields by adding a class to the input field when it is selected

Binding events like this is inefficient:

$('#entryform input).bind('focus', function(){
}).bind('blur', function(){

We need to listen for focus acquisition and focus loss at the parent level:

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

The parent element ACTS as a dispatcher and can bind events based on the target element.

8. Eliminate invalid queries

While jquery gracefully handles situations where there are no matching elements, it takes time to find them. If you only have one global js on your site, you'll most likely cram all of your jquery functions into $(document)ready(function(){// all the code you're proud of}.

Most effective methods are to use inline initializers so that your template can control exactly where and when js should be executed.

For example, for your "article" page template, you might reference the following code at the end of the body:

< The script type = "text/javascript>
Mylib. The article. The init ();
< / script>
< / body>

If your page template contains variable modules that may not appear on the page, or if you need them to load quickly for visual presentation, you can follow the initialization function to the module.

< 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>
< The script type = "text/javascript>
Mylib. Traffic_light. The init ();
< / script>

Your global js library might look like this:

Var mylib =
              Init: function ()
                    // Article specific jQuery functions.
            Init: function ()
                  // Traffic light unique jQuery function.

Delay to $(window).load

Jquery has an enticing feature for developers that allows you to fake events by hanging anything under $(document).ready. You'll find this in most examples.

Although $(document).rady is really useful, it can be executed while the page is being rendered and the other elements are not downloaded.

You can reduce the CPU usage of the page load by binding the jquery function to the $(window).load event. Iframe>) Execute after being downloaded.

$(window). The load (the function () {
JQuery function initialized after the page is fully loaded.

Redundant features such as drag and drop, visual effects and animation, preloading hidden images, etc. Are all suitable for this technique.

Related articles: