Sometimes when we write jQuery, for the convenience of writing code, we often ignore the pressure brought to the client during program execution. Along with this comes problems such as slow running speed or even inability to run on some low-end browsers or low-end computers.
Therefore, it is necessary for us to optimize our own jquery code to achieve faster and smoother operation.
Advanced techniques for jquery performance optimization. The following mainly introduces jquery performance optimization from seven aspects:
1. Introduce jQuery library through CDN (Content Delivery Network)
2. Reduce DOM operations
3. Use native JS appropriately
4. Selector optimization
5. Caching jQuery objects
6. Define a reusable function
7. Use array method to traverse jQuery object collection
The specific instructions for each method are explained below:
Introducing the jQuery library through CDN (Content Delivery Network)
The simplest step to improve the performance of JavaScript in your website is to introduce the latest version of the jQuery library. The newly released version usually has better performance improvements and fixes some bugs. Or introducing it through CDN is also a good choice. Introduction through CDN can reduce the loading time of the website.
Here are some CDN services:
<!-- Case 1 - jQuery CDN --> <script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script> <!-- Case 2 - requesting jQuery from Googles CDN (notice the protocol) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script> <!-- Case 3 - requesting the latest minor 1.10.x version (only cached for an hour) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js" ></script> <!-- Case 4 - requesting the absolute latest jQuery version (use with caution) --> <script src="http://code.jquery.com/jquery.min.js" ></script>
Some domestic CDN services:
http://www.bootcdn.cn/jquery/ <!--新浪 CDN--> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <!--百度 CDN--> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <!--Bootstrap CDN--> http://www.bootcdn.cn/jquery/
Reduce DOM operations
Although JavaScript performance has been greatly improved, DOM operations are still very resource-intensive, and DOM operations need to be reduced. This is especially important when inserting a large number of elements into a page.
For example:
<div id="elem" ></div> // 不好的方式 //var elem = $('#elem'); //for(var i = 0; i < 100; i++){ // elem.append('<li>element '+i+'</li>'); //} // 好的方式 var elem = $('#elem' ), arr = []; for(var i = 0; i < 100; i++){ arr. push('<li>element ' +i+'</li>' ); } elem. append(arr. join('' ));
Caching all elements and inserting them once will improve performance because only one redraw of the page is triggered. The same is true for CSS style properties.
More reading: Front-end page stuck? It may be caused by DOM operations, you need to optimize the code
Use native JS appropriately
Creating jQuery objects brings some overhead. Therefore, if performance is more important, use native javascript as much as possible. In some ways it might be easier to understand and require less code to write. For example:
// 打印list中的li的id $('#colors li' ). each(function(){ //将$(this).attr('id')方法替换为直接通过ID属性访问 console. log(this. id); })
Selector Optimization
If you need better performance but still want to use jQuery, you can try some jQuery selector optimization. The following is a test program that records the execution time of different selectors through the browser's console console.time and console.timeEnd methods.
HTML:
<div id="peanutButter" > <div id="jelly" class=".jellyTime" ></div> </div> JS: //测试程序 var iterations = 10000, i; //-------------------------------------------- //Case 1: 很慢 console.time('Fancy'); for (i = 0; i < iterations; i++) { $('#peanutButter div:first'); } console.timeEnd('Fancy'); //-------------------------------------------- //Case 2: 比较好,但仍然很慢 console.time('Parent-child'); for (i = 0; i < iterations; i++) { $('#peanutButter div'); } console.timeEnd('Parent-child'); //-------------------------------------------- //Case 3: 一些浏览器会比较快 console.time('Parent-child by class'); for (i = 0; i < iterations; i++) { // 通过后代Class选择器 $('#peanutButter .jellyTime'); } console.timeEnd('Parent-child by class'); //-------------------------------------------- //Case 4: 更好的方式 console.time('By class name'); 21 for (i = 0; i < iterations; i++) { // 直接通过Class选择器 $('.jellyTime'); } console.timeEnd('By class name'); //-------------------------------------------- //Case 5: 推荐的方式 ID选择器 console.time('By id'); for (i = 0; i < iterations; i++) { $('#jelly'); } console.timeEnd('By id');
Execution result:
Caching jQuery objects
Every time a new jQuery object is constructed through a selector, the Sizzle engine at the core of jQuery will traverse the DOM and match the real dom element through the corresponding selector. This method is relatively inefficient. In modern browsers, you can use the document.querySelector method to match the corresponding element by passing in the corresponding Class parameter. However, versions below IE8 do not support this method. One practice to improve performance is to cache jQuery objects via variables. For example:
<ul id="pancakes" > <li>first</li> <li>second</li> <li>third</li> <li>fourth</li> <li>fifth</li> </ul>
JS:
// 不好的方式: // $('#pancakes li').eq(0).remove(); // $('#pancakes li').eq(1).remove(); // $('#pancakes li').eq(2).remove(); // ------------------------------------ // 推荐的方式: var pancakes = $('#pancakes li'); pancakes.eq(0).remove(); pancakes.eq(1).remove(); pancakes.eq(2).remove(); // ------------------------------------ // 或者: // pancakes.eq(0).remove().end() // .eq(1).remove().end() // .eq(2).remove().end();
Define a reusable function
Go directly to the example:
HTML: <button id="menuButton" >Show Menu!</button> <a href="#" id="menuLink" >Show Menu!</a>
JS:
//Bad: //这个会导致多个回调函数的副本占用内存 $('#menuButton, #menuLink' ). click(function(){ // ... }); //---------------------------------------------- //Better function showMenu(){ alert('Showing menu!' ); // Doing something complex here } $('#menuButton' ). click(showMenu); $('#menuLink' ). click(showMenu);
If you define an inline callback function with a jQuery object containing multiple elements (as in the first example above), a callback function will be saved in memory for each element in the collection. copy of.
Use array method to traverse jQuery object collection
You may not have noticed, but this elegant implementation of the jQuery each method comes at a cost in terms of performance. There is a faster way to iterate over a jQuery object. It is implemented through an array. The jQuery object collection is an array-like object with length and value attributes. You can test the performance through the program:
HTML:
<ul id="testList" > <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <!-- add 50 more --> </ul>
JS:
var arr = $('li'), iterations = 100000; //------------------------------ // Array实现: console.time('Native Loop'); for (var z = 0; z < iterations; z++) { var length = arr.length; for (var i = 0; i < length; i++) { arr[i]; } } console.timeEnd('Native Loop'); //------------------------------ // each实现: console.time('jQuery Each'); for (z = 0; z < iterations; z++) { arr.each(function(i, val) { this; }); } console.timeEnd('jQuery Each');
Result:
You can see that traversal through array implementation has higher execution efficiency.
//------------------------------------------------ -------Continuous updates...
The above is a summary of some collected knowledge. If you have any suggestions or questions, please leave a message for discussion.

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

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