Optimize Jquery and improve web page loading speed_jquery
jquery
load
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:
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 classThe 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:
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:
div>
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('
}
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 = '
- ';
- ' top_100_list[i] ' ';
for (var i=0, l=top_100_list.length; i
top_100_ul = '
}
top_100_ul = '
$ 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
$(window).load(function(){
// jQuery function initialized after the page is fully loaded.
});
Redundant features such as drag and drop, visual effects and animations, preloading hidden images, etc. are all suitable for this technology.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article
Assassin's Creed Shadows: Seashell Riddle Solution
3 weeks ago
By DDD
What's New in Windows 11 KB5054979 & How to Fix Update Issues
2 weeks ago
By DDD
Where to find the Crane Control Keycard in Atomfall
3 weeks ago
By DDD
Assassin's Creed Shadows - How To Find The Blacksmith And Unlock Weapon And Armour Customisation
1 months ago
By DDD
Roblox: Dead Rails - How To Complete Every Challenge
3 weeks ago
By DDD

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
CakePHP Tutorial
1387
52



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:
