Some tips for writing efficient JSLite code imitating JQuery_jquery
It is not uncommon for articles to discuss jQuery and javascript performance. However, I plan to teach you how to improve your JSLite and JavaScript code based on some speed tips and suggestions that others have put together for jQuery. Good code will bring speed improvements. Fast rendering and responsiveness means a better user experience.
First of all, keep in mind that JSLite is javascript. This means we should adopt the same coding conventions, style guides and best practices.
First of all, if you are a javascript newbie and have never used jQuery, I suggest you read the syntax introduction of the official document first. This is a high-quality javascript tutorial, which means that you have been using jQuery for a while. .
When you are ready to use JSLite, I strongly recommend that you follow these guidelines:
Cache variables
DOM traversal is expensive, so try to cache reused elements.
// Oops
h = $('#element').height();
$('#element').css('height',h-20);
// Suggestion
$element = $('#element');
h = $element.height();
$element.css('height',h-20);
Avoid global variables
JSLite is the same as JavaScript. Generally speaking, it is best to ensure that your variables are within function scope.
// Oops
$element = $('#element');
h = $element.height();
$element.css('height',h-20);
// Suggestion
var $element = $('#element');
var h = $element.height();
$element.css('height',h-20);
Use Hungarian nomenclature
Add $ prefix before variables to easily identify JSLite objects.
// Oops
var first = $('#first');
var second = $('#second');
var value = $first.val();
// Suggestion - Prefix JSLite objects with $
var $first = $('#first');
var $second = $('#second'),
var value = $first.val();
Use var chain (single var mode)
Consolidate multiple var statements into one statement. I recommend putting unassigned variables at the end.
var $first = $('#first'),
$second = $('#second'),
Value = $first.val(),
k = 3,
Cookiestring = 'SOMECOOKIESPLEASE',
i,
j,
MyArray = {};
Please use on
In the new version of JSLite, the shorter on("click") is used to replace functions like click(). In previous versions on() was bind() . on() is the preferred method of attaching event handlers. However, for consistency's sake, you can simply use the on() method all together.
// Oops
$first.click(function(){
$first.css('border','1px solid red');
$first.css('color','blue');
});
$first.hover(function(){
$first.css('border','1px solid red');
})
// Suggestion
$first.on('click',function(){
$first.css('border','1px solid red');
$first.css('color','blue');
})
$first.on('hover',function(){
$first.css('border','1px solid red');
})
Streamlined javascript
In general, it’s best to combine functions whenever possible.
// Oops
$first.click(function(){
$first.css('border','1px solid red');
$first.css('color','blue');
});
// Suggestion
$first.on('click',function(){
$first.css({
'border':'1px solid red',
'color':'blue'
});
});
Chain operation
It is very easy to implement chained operations of methods in JSLite. Take advantage of this below.
// Oops
$second.html(value);
$second.on('click',function(){
alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'},500);
// Suggestion
$second.html(value);
$second.on('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
Maintain code readability
Along with streamlining the code and using chaining, the code may become difficult to read. Adding pinches and line breaks can work wonders.
// Oops
$second.html(value);
$second.on('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
// Suggestion
$second.html(value);
$second
.on('click',function(){ alert('hello everybody');})
.fadeIn('slow')
.animate({height:'120px'},500);
Select short-circuit evaluation
Short-circuit evaluation is an expression that is evaluated from left to right, using the && (logical AND) or || (logical OR) operators.
// Oops
function initVar($myVar) {
If(!$myVar) {
$myVar = $('#selector');
}
}
// Suggestion
function initVar($myVar) {
$myVar = $myVar || $('#selector');
}
Select shortcut
One way to streamline your code is to take advantage of coding shortcuts.
// Oops
if(collection.length > 0){..}
// Suggestion
if(collection.length){..}
Separating elements during heavy operations
If you plan to do a lot of operations on DOM elements (setting multiple attributes or css styles in succession), it is recommended to separate the elements first and then add them.
// Oops
var
$container = $("#container"),
$containerLi = $("#container li"),
$element = null;
$element = $containerLi.first();
//... Many complex operations
// better
var
$container = $("#container"),
$containerLi = $container.find("li"),
$element = null;
$element = $containerLi.first().detach();
//... Many complex operations
$container.append($element);
Memory skills
You may be inexperienced with using methods in JSLite, be sure to check out the documentation, there may be a better or faster way to use it.
// Oops
$('#id').data(key,value);
// Suggestion (efficient)
$.data('#id',key,value);
Parent element cached using subquery
As mentioned earlier, DOM traversal is an expensive operation. A typical approach is to cache parent elements and reuse these cached elements when selecting child elements.
// Oops
var
$container = $('#container'),
$containerLi = $('#container li'),
$containerLiSpan = $('#container li span');
// Suggestion (efficient)
var
$container = $('#container '),
$containerLi = $container.find('li'),
$containerLiSpan= $containerLi.find('span');
Avoid universal selectors
Putting the universal selector into a descendant selector has terrible performance.
// Oops
$('.container > *');
// Suggestion
$('.container').children();
Avoid implicit universal selectors
Universal selectors are sometimes implicit and difficult to find.
// Oops
$('.someclass :radio');
// Suggestion
$('.someclass input:radio');
Optimization selector
For example, the Id selector should be unique, so there is no need to add additional selectors.
// Oops
$('div#myid');
$('div#footer a.myLink');
// Suggestion
$('#myid');
$('#footer .myLink');
Avoid multiple ID selectors
I emphasize here that the ID selector should be unique, there is no need to add additional selectors, and there is no need for multiple descendant ID selectors.
// Oops
$('#outer #inner');
// Suggestion
$('#inner');
Stick to the latest version
New versions are usually better: more lightweight, more efficient, with more methods, and more comprehensive coverage of jQuery methods. Obviously, you need to consider the compatibility of the code you want to support. For example, does the project run on good support for HTML5/CSS3
Combine JSLite and javascript native code when necessary
As mentioned above, JSLite is javascript, which means that anything you can do with JSLite can also be done with native code. Native code may not be as readable and maintainable as JSLite, and the code may be longer. But it also means more efficient (usually the closer to the underlying code the less readable the higher the performance, for example: assembly, which of course requires more powerful people). Keep in mind that no framework can be smaller, lighter, and more efficient than native code (note: the test link is no longer valid, you can search for the test code online).
Final advice
Finally, I record this article with the purpose of improving the performance of JSLite and some other good suggestions. If you want to delve deeper into this topic you will find a lot of fun. Remember, JSLite is not required, just an option. Think about why you want to use it. DOM manipulation? ajax? stencil? css animation? Or a selector? Heavy jQuery developer?

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

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

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
