38 suggestions for jQuery performance optimization_jquery
1. Pay attention to adding the var keyword when defining jQuery variables
This is not just jQuery, but also needs to be paid attention to in all javascript development processes. Please do not define it as follows:
$loading = $('#loading'); //This is a global definition. If you accidentally reference the same variable name somewhere, you will be depressed to death
2. Please use a var to define Variables
If you use multiple variables, please define them as follows:
$loading = $('#loading'),
$body = $('body');
Don’t add it to every variable A var keyword, unless you have severe obsessive-compulsive disorder
3. Define jQuery variables by adding the $ symbol
When declaring or defining variables, please remember that if you are defining jQuery Variable, please add a $ sign in front of the variable, as follows:
The advantage of defining it like this is that you can effectively remind yourself or other users who read your code that this is a jQuery variable.
4. Please remember cache when operating DOM
In jQuery code development, we often need to operate DOM. DOM operation is a very resource-consuming process, and often many people Everyone likes to use jQuery like this:
$('#loading' ).html('Complete');
$('#loading').fadeOut();
There is no problem with the code. You can also run it normally and get results, but be careful every time you define it. And when calling $('#loading'), a new variable is actually created. If you need to reuse it, remember to define it in a variable, so that the variable content can be effectively cached, as follows:
$loading. html('Finished');$loading.fadeOut();
This will provide better performance.
5. Use chain operations
For the above example, we can write it more concisely:
var $loading = $('#loading');
$loading.html('Complete').fadeOut();
6. Streamline jQuery code
Try to integrate some codes together, please do not code like this:
//! ! Villain
$button.click(function(){
$target.css('width','50%');
$target.css('border','1px solid #202020' );
$target.css('color','#fff');
});
should be written like this:
$target.css({'width':'50%','border ':'1px solid #202020','color':'#fff'});
});
7. Avoid using global type selectors
Do not write as follows: $('.something > *');
It is better to write like this: $('.something').children();
8. Do not overlap multiple IDs
Please do not write as follows: $('#something #children');
This is enough: $('#children');
9. Use more logical judgments || Or && to speed up
Do not write as follows:
if(!$something) {
$something = $('#something ');
}
Writing performance is better this way:
10. Try to use less code
Instead of writing like this: if(string.length > 0){..}
Write it like this: if(string.length) {..}
11. Try to use the .on method
If you use a newer version of the jQuery class library, please use .on. Any other methods will eventually use .on. to achieve.
12. Try to use the latest version of jQuery
The latest version of jQuery has better performance, but the latest version may not support ie6/7/8, so you need to adjust it according to the actual situation Situation selection.
13. Try to use native Javascript
If the functions provided by jQuery can also be implemented using native Javascript, it is recommended to use native javascript to achieve it.
14. Always inherit from the #id selector
This is a golden rule for jQuery selectors. The fastest way to select an element in jQuery is to select it by ID.
Or inherit from the ID selector to select multiple elements:
15. Use tag in front of class
The second fastest selector in jQuery is the tag selector (such as $('head')), because it comes directly from the native Javascript method getElementByTagName(). So it’s best to always use tags to modify classes (and don’t forget the nearest ID)
The class selector in jQuery is the slowest because it will traverse all DOM nodes under IE browser. Try to avoid using class selectors. Don't use tags to modify IDs either. The following example will traverse all div elements to find the node with the id 'content':
Using ID to modify ID is superfluous:
16. Use subquery
to cache the parent object for future use
var menu = header.find('.menu');
// or
var menu = $('.menu', header);
17. Optimize the selector with Applicable to Sizzle's "right-to-left" model
Since version 1.3, jQuery uses the Sizzle library, which is very different from the previous version in the way it behaves on the selector engine. It replaces the "right to left" model with a "left to right" model. Make sure the rightmost selector is specific and the left selector is broad:
instead of using
18. Use find( ), it is indeed faster to find the
.find() function without using context. But if a page has many DOM nodes, it may take more time to search back and forth:
var divs = $('#pageBody').find('.testdiv'); // 2324 on Firebug 3.6 - The best time
var divs = $('#pageBody .testdiv'); // 2469 on Firebug 3.6
19. Write your own selector
If you often use selectors in your code, then extend jQuery’s $.expr[':'] object and write your own selector. In the following example, I created an abovethefold selector to select invisible elements:
abovethefold: function(el) {
return $(el).offset().top < $(window) .scrollTop() $(window).height();
}
});
var nonVisibleElements = $('div:abovethefold'); // Select element
20. Caching jQuery objects
Cache elements you frequently use:
var header = $('#header');
var divs = header.find('div');
var forms = header.find('form') ;
When DOM insertion is required, encapsulate all elements into one element
21. Direct DOM operation is very slow. Change the HTML structure as little as possible.
var menu = ' ';
$('#header').prepend(menu);
// Never do this:
$('#header'). prepend(' ');
for (var i = 1; i < 100; i ) {
$('#menu'). append('
}
22. Although jQuery does not throw exceptions, developers should also inspect objects
Although jQuery will not throw a large number of exceptions to users, developers should not rely on this. jQuery usually executes a bunch of useless functions before determining whether an object exists. So before making a series of references to an object, you should first check whether the object exists.
Twenty-three. Use direct functions instead of equivalent functions
For better performance, you should use direct functions such as $.ajax() instead of Use $.get(), $.getJSON(), $.post(), because the latter ones will call $.ajax().
24. Cache jQuery results for later use
You will often get a javasript application object - you can use App. to save the objects you often select for future use Use:
App.hiddenDivs = $('div.hidden ');
// Then call in your application:
App.hiddenDivs.find('span');
25. Use jQuery’s internal function data( ) to store the state
Don’t forget to use the .data() function to store information:
$('#head').data('name', 'value');
// Then call it in your application:
$('# head').data('name');
26. Use jQuery utility function
Don’t forget the simple and practical jQuery utility function. My favorites are $.isFunction(), $isArray() and $.each().
Twenty-seven. Add the class "JS" to the HTML block
When jQuery is loaded, first add a class called "JS" to the HTML
Only when the user You can only add CSS styles when JavaScript is enabled. For example:
.JS # myDiv{display:none;}
So when JavaScript is enabled, you can hide the entire HTML content and use jQuery to achieve what you want (for example: collapse certain panels or expand them when the user clicks on them). When Javascript is not enabled, the browser renders all content, and search engine crawlers will also remove all content. I will use this technique more in the future.
28. Defer to $(window).load
Sometimes $(window).load() is faster than $(document).ready() because the latter Executed before all DOM elements have been downloaded. You should test it before using it.
29. Use Event Delegation
When you have many nodes in a container and you want to bind an event to all nodes, delegation is very suitable for such application scenarios. Using Delegation, we only need to bind the event at the parent and then see which child node (target node) triggered the event. This becomes very convenient when you have a table with a lot of data and you want to set events on the td node. First get the table, and then set delegation events for all td nodes:
$(this).toggleClass("hover");
});
30. Use the abbreviation of ready event
If you want to compress the js plug-in and save every byte, you should avoid using $(document).onready()
$(document).ready(function (){
// Code
});
// You can abbreviate it like this:
$(function (){
// Code
});
31. jQuery Unit Testing
The best way to test JavaScript code is to have people test it. But you can use some automated tools such as Selenium, Funcunit, QUit, QMock to test your code (especially plug-ins). I want to discuss this topic in another topic because there is so much to say.
ThreeTwelve. Standardize your jQuery code
Standardize your code often to see which query is slower and replace it. You can use the Firebug console. You can also use jQuery's shortcut functions to make testing easier:
// Shortcut to record data in Firebug console
$.l($('div'));
// Get UNIX timestamp
$.time();
// Record code execution time in Firebug
$.lt();
$('div');
$.lt();
// Put the code block in a for loop to test the execution time
$.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug 3.6
33. Use HMTL5
The new HTML5 standard brings a lighter DOM structure. A lighter structure means fewer traversals are required when using jQuery, and better loading performance. So please use HTML5 if possible.
34. If you want to add styles to more than 15 elements, add style tags directly to the DOM elements
To add styles to a few elements, the best way is to use jQuey css() function. However, when adding styles to more than 15 elements, it is more effective to add style tags directly to the DOM. This method avoids using hard code in the code.
$('')
.appendTo('head');
35. Avoid loading redundant code
It is a good idea to put Javascript code in different files and load them only when needed. This way you won't load unnecessary code and selectors. It is also easy to manage code.
36. Compress into one main JS file and keep the number of downloads to a minimum
When you have determined which files should be loaded, package them into one file . Use some open source tools to automatically do it for you, such as using Minify (integrated with your back-end code) or using online tools such as JSCompressor, YUI Compressor or Dean Edwards JS packer to compress files for you. My favorite is JSCompressor.
37. Use native Javascript when needed
Using jQuery is a great thing, but don’t forget that it is also a framework for Javascript. So you can use native Javascript functions when necessary in jQuery code, which can achieve better performance.
38. Lazy load content for speed and SEO benefits not only improves loading speed, but also improves SEO optimization (Lazy load content for speed and SEO benefits)
Use Ajax to load your website Well, this can save server-side loading time. You can start with a common sidebar widget.

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

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



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 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

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

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: <

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

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:

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 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
