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.
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.
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:
$('# 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');
$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:
// 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:
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:
div>
For example, we can use the subquery method to capture the lights that are on or off, and cache them for subsequent operations.
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:
var top_100_list = [...], // Assume here are 100 unique strings
$mylist = $('#mylist'); // jQuery selects 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:
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:
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:
$('#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:
$('#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.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.


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

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft