


25 steps to improve your jQuery and improve efficiency by a thousand times_jquery
1. Load jQuery from Google Code
Google Code has hosted a variety of JavaScript libraries. Loading jQuery from Google Code is better than loading it directly from your server. More advantages. It saves bandwidth on your server and can quickly load JS libraries from Google's Content Distribution Network (CDN). More importantly, if a user visits a site published on Google Code it will be cached.
This makes sense. How many sites use the same copy of jQuery that isn't cached, and this is easy to do, introduce:
2. Use the cheat sheet
Not only jQuery, many programming languages also have similar cheat sheets, in an A4 It's easy to see how each function is used on paper. Fortunately, some kind people have already made a perfect jQuery cheat sheet:
http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat -sheet/
http://colorcharge.com/jquery/
3. Consolidate all scripts and minify them
Yes, this is a common JavaScript trick. However, a large project that uses jQuery may use many related jQuery plug-ins (this site uses easing, localScroll, lightbox, preload), so it is usually applicable. Browsers cannot load JS scripts at the same time (in most cases), which means that if you load many scripts at the same time, it will slow down the loading speed of the page. Therefore, if these scripts are to be loaded on every page, you should consider consolidating these scripts into a slightly larger JS script before publishing. Some jQuery plugins are already minified, but you should package your JS scripts and those that are not minified, which only takes a few seconds to complete.
Personally, I recommend Packer by Dean Edwards
4. Use Firebug’s excellent console logging tool
If you don’t have Firebug installed yet, you really should. In addition to many other useful features (such as allowing you to inspect http traffic and find problems with your CSS), it also has excellent logging commands that allow you to easily debug JS scripts.
Here are detailed descriptions of all features of Firebug .
My favorite feature is "console.info", which allows you to output information and variable values to the console without having to use alert;" console. time" allows you to set a timer on a set of code to calculate the time it takes for the JS script to run. It's all easy to do:
console.time( 'create list');
for (i = 0; i var myList = $('.myList');
myList.append('This is list item ' i);
}
console.timeEnd('create list');
5. Minimize selection operations through caching
jQuery’s selectors are awesome. They are an extremely simple way to find any element on the page, but internally they have to go through a lot of steps to perform the selection operation, and if you use them incorrectly, you may find that everything slows down quite a bit.
If you select the same element again and again (e.g. in a loop), then you can select it once and put it in memory, while you can manipulate it in the core content. Look at the example below. Here we use a loop to add entries to UL:
for (i = 0; i var myList = $('.myList');
myList.append('This is list item ' i);
}
This took 1066 milliseconds on my PC in Firefox 3 (imagine that in IE6!), which is quite slow for JavaScript. Now let's take a look at the following code, where we only use one selection operation:
var myList = $('.myList');
for (i = 0; i myList.append('This is list item ' i) ;
}
It only took 224 milliseconds, which is nearly 4 times faster by moving one line of code.
6. Minimize DOM operations
We can make the above code run faster by reducing insertion operations into the DOM. DOM insertion operations (such as .append(), .prepend(), .after(), .wrap()) are quite time-consuming, and performing these operations will slow down the running of the program.
All we have to do is use string concatenation to construct a list of items and add the items to the list using a function, such as .html(). Please see the following example:
var myList = $(' #myList');
for (i=0; imyList.append('This is list item ' i);
}
On my PC it took 216ms, which is just around 1/5 second. But if we use strings to construct list items, use the following HTML method to complete the insertion operation:
var myList = $('.myList');
var myListItems = '';
for (i = 0; i myListItems = '
}
myList.html(myListItems);
It took 185 milliseconds, although not as fast A lot, but it also improved the time by 31 milliseconds.
7. When dealing with DOM insertion operations, wrap the required content in an element
Well, don’t ask me why I do this (I believe there is quite a An experienced programmer will explain it to you).
In the above example we use .html() to insert 1000 items into UL. If we wrap the items in a UL tag before the insert operation, and then insert the complete UL into another DIV tag, then we actually only insert one tag instead of 1000, which seems more efficient. Please look at the following example:
var myList = $(' .myList');
var myListItems = '
- ';
- This is list item ' i ' ';
for (i = 0; i myListItems = '
}
myListItems = '
myList.html(myListItems);
Now The time taken is only 19 milliseconds, which is a significant 50x improvement over our previous first example.
8. Use ID instead of class whenever possible
jQuery uses classes to select DOM elements as easily as selecting by ID, so it is more free than before The use of classes for element selection operations is very attractive. However, since jQuery uses the browser's inherent method (getElementById) for selection operations, it is more advantageous to use ID for selection operations. How fast? let's see.
I took the previous example and modified it so that each LI we create has a unique class. Then I will iterate through it, selecting one element at a time:
// Create our list
var myList = $('.myList');
var myListItems = '
- ';
- This is a list item ';
for (i = 0; i myListItems = '
}
myListItems = '
myList .html(myListItems);
// Select each item once
for (i = 0; i var selectedItem = $('.listItem' i);
}
As expected, my browser took 5066ms (over 5 seconds). So I modified the above code to use ID instead of class and then select by ID.
// Create our list
var myList = $('.myList');
var myListItems = '
- ';
- This is a list item ';
for (i = 0; i myListItems = '
}
myListItems = '
myList.html(myListItems);
// Select each item once
for (i = 0; i var selectedItem = $('#listItem' i);
}
It only took 61 milliseconds, almost 100 times faster
9. Provide context for selectors
By default, when you use a selector like $('.myDiv') it will search in the entire DOM document element, this comes at a significant cost.
When performing a selection operation, the jQuery function can specify a second parameter: jQuery(expression, context) By providing a context to the selector, the element search will be performed in this context instead of in the entire DOM document. Find elements.
To explain this, let’s use the first piece of code from before. It creates a UL with 1000 items, each with a separate class.
Then iterate and select one item at a time. You should remember that it takes more than 5 seconds to select all 1000 items by class.
var selectedItem = $('#listItem' i);
Then I added a context to it to perform the selection only in the UL:
var selectedItem = $('#listItem' i, $('.myList'));
Due to poor efficiency, still It took 3818 milliseconds, but still achieved a 25% speed increase with a small modification.
10. Use method chain correctly
One of the most cool features of jQuery is that jQuery can make continuous method calls. For example, you want to switch the class of an element:
$('myDiv').removeClass('off').addClass('on');
If you are like me, you may be able to use it further after learning jQuery in the first five minutes it. First of all, it can still operate across lines (jQuery is JavaScript), which means you can write neat code like this:
$('#mypanel')
.find('TABLE .firstCol')
.removeClass('.firstCol')
.css(' background' : 'red')
.append('This cell is now red');
The habit of using linked lists will help you reduce your choices use of the device. However you can go deeper and use it if you want to perform several functions on one element, but change the element of operation in some way:
$('#myTable').find('.firstColumn').css('background','red');
We selected a table, found the cell with class "firstColumn" in it, and then made its background red.
Now we want to set the background of all cells with class "lastColumn" to blue. Because we have used the find() function to filter out all cells whose class is not "firstColumn", we need to use the selection operation on the table again. Can't we make continuous method calls? Fortunately jQuery provides the end() function, which changes the matched element list to the previous state so that you can execute the method list:
$('#myTable')
.find('.firstColumn')
.css('background','red')
.end()
.find('.lastColumn')
.css('background','blue');
Write a method that can chain calls Custom jQuery functions are also easy. All you do is write a function that modifies an element and returns an element.
$.fn.makeRed = function() {
return $(this).css('background', 'red');
}
$('#myTable') .find('.firstColumn').makeRed().append('hello');
It's very simple!
11. Learn to use effects correctly
When I first started using jQuery, I liked this very much: it can easily use predefined various Animation effects, such as slideDown() and fadeIn(). Since the animate() method provided by jQuery is very easy to use and powerful, it is easy for us to use it in depth. In fact, many methods in the jQuery source code achieve effects through the animate() function.
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
fadeIn: function(speed, callback){
return this.animate({opacity: " show"}, speed, callback);
}
The animate() method only acts on CSS, converting smoothly based on the value. So you can change width, height, opacity, background color, top, left, margin, color, font size and whatever you want.
It is easy to add height changes to menu items:
$('#myList li').mouseover(function() {
$(this).animate({"height": 100}, "slow");
});
Unlike other jQuery functions, animation effects are automatically queued, so if you want to run a second effect after the first effect is completed, you need to call the animate method twice:
$('#myBox').mouseover(function() {
$(this).animate({ "width": 200 }, "slow");
$(this).animate({"height": 200}, "slow");
} );
If you want the animation effects to occur at the same time, you need to pass all styles into the method as a parameter object:
$('#myBox').mouseover(function() {
$(this).animate({ "width" : 200, "height": 200 }, "slow");
});
You can animate properties whose values are numbers. You can also download plug-ins to help you animate non-numeric properties, such as colors and background colors
12. Understanding event proxies
JQuery makes it easier than ever to seamlessly add events to DOM elements. This is a great feature, however adding too many events to an element is inefficient. In many cases event proxies allow you to achieve the same goal with a smaller number of events. The best way to explain is to use examples:
$(' #myTable TD').click(function(){
$(this).css('background', 'red');
});
When we click on the table The above code will make all cell backgrounds red. For example, if you have a grid with 10 columns and 50 rows, 500 events will be bound to it. Well, this is the time for the event proxy to appear:
$('#myTable').click(function(e) {
var clicked = $(e.target);
clicked.css('background', 'red');
});
e' contains event information, including the target element that actually received the click event. All we have to do is check which cell was clicked. Quite clever!
Event proxies bring another benefit. Normally, when you bind an event to a collection of elements, the event is only bound to the collection elements. If you add new elements to the DOM, even though these new elements are matched by the selector, these new elements are not bound to event handlers (do you agree with me?), so no events will occur.
When using event proxies, you can still add multiple matched elements to the event after it is bound to the DOM, and they will still work normally.
13. Use classes to store state
This is the most basic way to store information in html. jQuery is good at manipulating elements based on classes, so if you need to store state information about an element, why not try using an additional class to store it?
Here is an example. We want to create an expanded menu. When you click the button, we want to expand and contract the menu through slideDown() and slideUp(). Please look at the HTML below:
Very simple! We just add an extra class to the wrapper DIV, which just tells us the status of the item. So all we need after the button is clicked is click event handling, which will execute the corresponding slideUp() and slideDown() methods.
$('.button').click(function( ) {
var menuItem = $(this).parent();
var panel = menuItem.find('.panel');
if (menuItem.hasClass("expanded ")) {
menuItem.removeClass('expanded').addClass('collapsed');
panel.slideUp();
}
else if (menuItem.hasClass("collapsed") ) {
menuItem.removeClass('collapsed').addClass('expanded');
panel.slideDown();
}
});
This is a very simple example, but you can add additional classes to an element or HTML fragment to store all kinds of information.
However, in addition to simple situations we should use the following technique.
14. A better way is to use jQuery’s built-in data() method to store the state
For some reasons, there is no good documentation in this regard. jQuery provides the built-in data() method, which, unlike DOM elements, can be used to store key/value type data. The storage of data is very easy:
$('# myDiv').data('currentState', 'off');
We modify the code of the previous example so that we can use the same HTML content (except without the "expanded" class) and Use the data() function to store the state:
$ ('.button').click(function() {
var menuItem = $(this).parent();
var panel = menuItem.find('.panel');
if (menuItem.data('collapsed')) {
menuItem.data('collapsed', false);
panel.slideDown();
}
else {
menuItem.data('collapsed', true);
panel.slideUp();
}
});
I believe you will also agree that the use of this method is indeed more sophisticated. For more information on data() and removeData(), please check out jQuery internals
15. Write your own selectors
jQuery has many built-in selectors for selecting by ID, class, tag, attribute and other elements. However, what can you do when you need to select elements based on some other content and jQuery does not provide this selector?
Well, one solution might be to add classes to the elements from the beginning, and then use these classes for element selection operations. However this has proven difficult to extend jQuery with new selectors.
The best way to explain is to use examples:
$.extend($.expr[':'], {
over100pixels: function(a) {
return $(a).height() > 100;
}
});
$('.box:over100pixels').click(function() {
alert('The element you clicked is over 100 pixels high');
});
The previous part of the code creates a custom selector that finds all elements longer than 100px. The following code simply binds the click event to those elements found using the selector.
I won’t give a more detailed explanation here, but you can imagine how powerful it is! If you search "custom jquery selector" on Google, you will see many examples of this.
16. Minimize your HTML and modify it after the page loads
This title may not mean much, but this trick may streamline your code, reduce code size and page downloads time to help optimize your search engines. Please see the example below:

< ;div class="message">This is an error message

The above is a specific example of HTML, slightly modified for explanation purposes. I believe you will also think this code is quite ugly. If the code like this is very long, you will end up with a rather long and ugly page. So you can handle it like this:
All you have to do is add the ugly HTML back after the page has finished loading via a jQuery operation:
$(document).ready(function() {
$('.field').before('
$('.field').after('

});
It is not always advisable to do this, you will see the page flash for a moment after the page loads, but in certain cases you have a lot of repeated HTML content, then through this method you can display Significantly reducing page code size and reducing irrelevant and repetitive tags can benefit your SEO.
17. For speed and SEO considerations, delay loading of content
There is also a way to improve page loading speed and smooth out the HTML content searched by Spiders. By using AJAX requests to load additional content later after the page has loaded, users can start browsing right away and let spiders see the content you want them to index.
We already use this technology on our own website. The purple button at the top of this page will pop up three tables, directions and Google Maps, which will triple the size of our page. So we only need to put these HTML contents into a static page, and load it through the load() function after the page is loaded:
$('#forms').load('content/headerForms.html', function() {
// Code here runs once the content has loaded
// Put all your event handlers etc. here.
});
I wouldn’t use this trick everywhere on the page. You have to weigh this up. You need to make additional page requests, and some of the content on the page cannot be immediately displayed to the user, but using this technique correctly can be very helpful for optimization.
18. Use the tool functions provided by jQuery
jQuery has more than just flash effects. The jQuery author also provides some quite practical methods, which fill in some of the shortcomings of JacaScript.
http://docs.jquery.com/Utilities
In particular, providing browser support for some common array functions is a patch. jQuery provides methods to iterate, filter, clone, merge, and remove duplicates from an array.
Other commonly used functions include getting the selection in the drop-down box. With traditional JavaScript methods, you would have to use getElementById to get the

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

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

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
