1. Load jquery from Google Code
Google Code has hosted a variety of JavaScript class libraries. Loading jquery from Google Code is more advantageous than loading it directly from your server. ItSaves the bandwidth on your serverTo quickly load JS class libraries from Google's Content Distribution Network (CDN. More importantly, if a user accesses a site published on Google codeCache.
This is meaningful. How many sites use the same jquery copy that has not been cached, which is easy to achieve. Introduction:
<SCRIPT type = "text/JavaScript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"> </SCRIPT>
2. Use the memo form
Not just jquery, but manyProgramming LanguageThere are similar memo sheets, so you can easily see the usage of each function on an A4 paper. Fortunately, there are good guys who have made jquery's memo sheet perfect:
Http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
Http://colorcharge.com/jquery/
3. Integrate all scripts and reduce them
Yes. This is a common JavaScript technique. However, a large project that uses jquery may use many related jquery plug-ins (easing, localscroll, lightbox, and preload are used on this site), so it is usually applicable. The browser cannot load JS scripts at the same time (in most cases), which means that if you load many scripts at the same time, the page loading speed will be slowed down. Therefore, if you need to load these scripts on each page, you should consider integrating these scripts into a slightly larger JS script before release. Some jquery plug-ins have been minimized, but you should package your JS scripts and those that have not been reduced, which takes only a few seconds to complete.
Personally, I recommend packer by Dean Edwards.
4. Use firebug's excellent console logging tool
If you have not installed firebug, you should install it. In addition to many other useful features (such as allowing you to check HTTP Transmission Conditions and find your CSS problems), it also has excellent log commands that allow you to easily debug JS scripts.
Here is a detailed description of all firebug features.
My favorite feature is "lele.info", which allows you to output information and variable values to the console without using alert; "console. Time" allows you to be in a groupCodeSet a timer to calculate the time it takes to run the JS script. It is easy to do this:
Copy code The Code is as follows: console. Time ('create list ');
For (I = 0; I <1000; I ++ ){
VaR mylist = $ ('. mylist ');
Mylist. append ('this is list item' + I );
}
Console. timeend ('create list ');
5. Minimize selection through caching
Jquery's selector is awesome. They can find any element in an extremely simple way on the page, but they can be selected only through a large number of internal steps. If you use them incorrectly, then you may find that everything has become quite slow.
If you select the same element again and again (for example, in a loop), you can select it and put it into the memory at a time, and you can operate on it in the core content. Let's take a look at the example below. Here we use a loop to add entries to Ul:Copy codeThe Code is as follows: for (I = 0; I <1000; I ++ ){
VaR mylist = $ ('. mylist ');
Mylist. append ('this is list item' + I );
}
It took 1066 milliseconds for Firefox 3 on my PC (you can imagine the situation in IE6 !), This operation is quite slow for JavaScript. Now let's take a look at the following code. Here we only use one selection operation:Copy codeThe Code is as follows: var mylist = $ ('. mylist ');
For (I = 0; I <1000; I ++ ){
Mylist. append ('this is list item' + I );
}
It took only 224 milliseconds to move a line of code nearly 4 times faster.
6. Minimize Dom operations
By reducing the DOM insertion Operation, we can make the above Code run faster. Dom insert operations (such as. append (),. prepend (),. After (),. Wrap () are quite time-consuming. Execution of these operations will slow down.Program.
What we want to do is to use serial concatenation to construct a listitem and use a serial number to construct these items, such as. html (). See the following example:
Copy code The Code is as follows: var mylist = $ ('# mylist ');
For (I = 0; I <1000; I ++ ){
Mylist. append ('this is list item' + I );
}
I spent 216 milliseconds on my PC, only about 1/5 seconds. However, if we use a string to construct a list item, use the following HTML method to complete the insert operation:Copy codeThe Code is as follows: var mylist = $ ('. mylist ');
VaR mylistitems = '';
For (I = 0; I <1000; I ++ ){
Mylistitems + = '<li> This is list item' + I + '</LI> ';
}
Mylist.html (mylistitems );
It takes 185 milliseconds. Although it is not much faster, it also increases by 31 milliseconds.
7. Wrap the required content in an element when processing Dom insert operations
Well, don't ask why I want to do this (I believe a programmer with considerable experience will explain it to you ).
In the example of examples, we use .html () to insert 1000 item items into ul. If we wrap these items in UL labels before the insert operation, and then insert the complete ul into another Div tag, We will insert only one tag instead of 1000, this looks more efficient. See the following example:Copy codeThe Code is as follows: var mylist = $ ('. mylist ');
VaR mylistitems = '<ul> ';
For (I = 0; I <1000; I ++ ){
Mylistitems + = '<li> This is list item' + I + '</LI> ';
}
Mylistitems + = '</ul> ';
Mylist.html (mylistitems );
the current time is only 19 ms, which is obviously 50 times higher than the previous example.
8. using ID instead of class as much as possible
jquery uses classes to select DOM elements as easily as using ID, therefore, it is more attractive to use classes for element selection than before. However, because jquery uses the inherent method of the browser (getelementbyid) for selection operations, the use of ID for selection operations is more advantageous. How fast is it? Let's take a look.
I used the previous example to modify it so that each Li we created has a unique class. Then I will traverse it and select an element each time: copy Code the code is as follows: // create our list
var mylist = $ ('. mylist');
var mylistitems = '
';
for (I = 0; I <1000; I ++) {
mylistitems + = '
- This Is a list item
';
}< br> mylistitems + = '
';
mylist.html (mylistitems );
// select each item once
for (I = 0; I <1000; I ++) {
var selecteditem = $ ('. listitem '+ I);
}
As I thought, my browser took 5066 milliseconds (more than 5 seconds ). Therefore, I modify the above Code to use ID instead of class, and then select through ID.Copy codeThe Code is as follows: // create our list
VaR mylist = $ ('. mylist ');
VaR mylistitems = '<ul> ';
For (I = 0; I <1000; I ++ ){
Mylistitems + = '<li id = "listitem' + I + '"> This Is a list item </LI> ';
}
Mylistitems + = '</ul> ';
Mylist.html (mylistitems );
// Select each item once
For (I = 0; I <1000; I ++ ){
VaR selecteditem = $ ('# listitem' + I );
}
It took only 61 milliseconds, almost 100 times faster
9. provide context for the selector
By default, when you use a selector similar to $ ('. mydiv'), you will search for elements in the entire DOM document at a high cost.
When the Select Operation is executed, the jquery function can specify the second parameter: jquery (expression, context) provides a context for the selector, and then performs element search in the context, instead of searching for elements in the entire DOM document.
To explain this, we use the first code. It creates a UL with 1000 Items and each item has a separate class.
Then, traverse and select one item at a time. You should remember that it takes more than five seconds to select all the 1000 items through the class.
Copy code Code: var selecteditem =$ ('# listitem' + I );
Then I add a context for it to perform the selection operation in UL only:Copy codeCode: var selecteditem =$ ('# listitem' + I, $ ('. mylist '));
Because the efficiency is too low, it still takes 3818 milliseconds, but a small modification still achieves a 25% speed increase.
10. Use method chain correctly
One of the most dazzling features of jquery is that jquery can continuously call methods. For example, you want to switch the class of an element:Copy codeThe Code is as follows: $ ('mydiv '). removeclass ('off'). addclass ('on ');
If you are like me, you may be able to use jquery for the first five minutes. First, it can still perform cross-line operations (jquery is JavaScript), which means you can write the following neat code:Copy codeThe Code is as follows: $ ('# mypanel ')
. Find ('table. firstcol ')
. Removeclass ('. firstcol ')
. CSS ('background': 'red ')
. Append ('<span> this cell is now red </span> ');
The habit of using the linked list will help you reduce the usage of selector. However, you can use it more deeply. You want to execute several functions on an element, but in some way you have changed the elements of the operation:Copy codeThe Code is as follows: ('{mytable'}.find('.firstcolumn'}.css ('background', 'red ');
Select a table, locate the cell with Class "firstcolumn", and change the background to red.
Now we want to set the background of all cells whose class is "lastcolumn" to blue. Because we have used the find () function to filter all cells whose class is not "firstcolumn", we need to use the selection operation for the table again, can't we call Methods consecutively? Fortunately, jquery provides the end () function, which changes the list of matched elements to the previous state so that you can execute the method linked list:Copy codeThe Code is as follows: $ ('# mytable ')
. Find ('. firstcolumn ')
. CSS ('background', 'red ')
. End ()
. Find ('. lastcolumn ')
. CSS ('background', 'blue ');
It is also easy to write a custom jquery function that can be called in a method chain. What you do is to write a function that can modify elements and return elements.Copy codeThe Code is as follows: $. FN. makered = function (){
Return background (this).css ('background', 'red ');
}
$ ('# Mytable'). Find ('. firstcolumn '). makered (). append ('hello ');
It's easy!
11. Learn to use results correctly
When I first started using jquery, I liked it very much: it can easily use a variety of predefined animation effects, such as slidedown () and fadein. The animate () method provided by jquery is very easy to use and powerful, so we can easily use it in depth. In factSource codeMany methods are implemented through the animate () function.
Copy code The Code is as follows: 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 applies to CSS and converts values smoothly. Therefore, you can change the width, height, transparency, background color, top, left, margin, color, font size, and anything you want.
It is easy to add a height change to a menu item:Copy codeThe Code is as follows: $ ('# mylist li'). Mouseover (function (){
$ (This). animate ({"height": 100}, "slow ");
});
Unlike other jquery functions, animation effects are automatically inserted into the queue. Therefore, if you want to run the second special effect after the first special effect is completed, you need to call the animate method twice:Copy codeThe Code is as follows: $ ('# mybox'). Mouseover (function (){
$ (This). animate ({"width": 200}, "slow ");
$ (This). animate ({"height": 200}, "slow ");
});
If you want to make the animation effect happen at the same time, you need to pass all styles into the method as a parameter object:Copy codeThe Code is as follows: $ ('# mybox'). Mouseover (function (){
$ (This). animate ({"width": 200, "height": 200}, "slow ");
});
You can add an animation effect to the attribute where the value is a number. You can also download the plug-in to help you add animation effects to attributes of non-numeric values, such as colors and background colors.
12. Understand event proxy
Compared with the previous one, jquery makes it easier to seamlessly add events to DOM elements. This is a great feature, but adding too many events to elements is inefficient. In many cases, the event proxy allows you to use a small number of events for the same purpose. The best way to explain this is to use an instance:
Copy code The Code is as follows: $ ('# mytable TD'). Click (function (){
Watermark (this).css ('background', 'red ');
});
When we click cells in the table, the above Code changes the background of all cells to red. For example, if you have a grid with 10 columns and 50 rows, you will bind the last 500 events. Well, it's time for the event agent to appear:Copy codeThe Code is as follows: $ ('# mytable'). Click (function (e ){
VaR clicked = require (e.tar get );
Clicked.css ('background', 'red ');
});
E' contains the event information, including the target element that actually receives the click event. All we have to do is check which cell is clicked. Pretty clever!
event proxy brings another benefit. Normally, when you bind an event to an element set, the event is only bound to these collection elements. If you add new elements to the Dom, although these new elements are matched by the selector, these new elements are not bound to event processing (Do you agree with me ?), Therefore, no event occurs.
when using the event proxy, you can still add multiple matched elements to the event after the event is bound to the Dom, and they work normally.
13. Use classes to store status
This is the most basic method for storing information in HTML. Jquery is good at element operations based on classes. Therefore, if you need to store the state information of an element, why not try to store it with an additional class?
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. See the following HTML: copy Code the code is as follows:
click me
- menu item 1
- menu item 2
- menu item 3
Very simple! We only add an extra class to the wrapper Div, which only tells us the status of the item. Therefore, after the button is clicked, all we need is the click event processing, which will execute the corresponding slideup () and slidedown () methods.Copy codeThe Code is as follows: $ ('. click'). 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 simple example, but you can add additional classes to an element or HTML segment to store all types of information.
However, in addition to simple cases, we should use the following technique.
14. A better way is to store the status using the built-in data () method of jquery.
For some reason, there is no good documentation for reference. Jquery provides the built-in data () method. Unlike DOM elements, jquery can be used to store data of the key/value type. Data storage is easy:Copy codeThe Code is as follows: $ ('# mydiv'). Data ('currentstate', 'off ');
We modified the code of the previous example so that we can use the same HTML content (except for the "expanded" class) and store the status using the data () function:Copy codeThe Code is as follows: $ ('. click'). 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 that you will agree that the use of this method is indeed more sophisticated. For more information about data () and removedata (), see jquery internals.
15. Write your own Selector
Jquery has many built-in selectors for selection through ID, class, Tag, attribute, and other elements. However, when you need to select elements based on other content, but jquery does not provide this selector, what can you do?
Well, a solution may be to add classes to the elements from the very beginning, so as to use these classes for element selection. However, this proves that it is difficult to extend the new selector to jquery.
The best way to explain this is to use an instance:Copy codeThe Code is as follows: $. Extend ($. expr [':'], {
Over100pixels: function (){
Returned $ (a). Height ()> 100;
}
});
$ ('. Box: over100pixels'). Click (function (){
Alert ('the element you clicked is over 100 pixels high ');
});
Create a custom selector in the first part of the code to identify all elements with a length greater than PX. The following code binds the click event to the elements found using the selector.
I will not explain it more specifically here, but you can imagine how powerful it is! If you search for "Custom jquery selector" on Google, you will see many examples in this regard.
16. Streamline your HTML and modify it after loading the page
This title may not be very interesting, but this technique may streamline your code, reduce the size of your code and the download time of the page, and help optimize your search engine. See the following example:
Copy code The Code is as follows: <Div class = "fieldouter">
<Div class = "inner">
<Div class = "field"> This is field number 1 </div>
</Div>
<Div class = "errorbar">
<Div class = "icon"> </div>
<Div class = "message"> <span> This is an error message </span> </div>
</Div>
</Div>
<Div class = "fieldouter">
<Div class = "inner">
<Div class = "field"> This is field number 2 </div>
</Div>
<Div class = "errorbar">
<Div class = "icon"> </div>
<Div class = "message"> <span> This is an error message </span> </div>
</Div>
</Div>
The above is a specific example of HTML, with a small amount of modifications made for the purpose of interpretation. I believe you will also think this code is quite ugly. If the code is very long, you will eventually form a very long and ugly page. Therefore, you can process it as follows:Copy codeThe Code is as follows: <Div class = "field"> This is Field 1 </div>
<Div class = "field"> This is Field 2 </div>
<Div class = "field"> This is Field 3 </div>
<Div class = "field"> This is field 4 </div>
<Div class = "field"> This is Field 5 </div>
all you need to do is add ugly HTML after page loading through jquery: copy Code the code is as follows: $ (document ). ready (function () {
$ ('. field '). before ('
');
$ ('. field '). after ('
This is an error message
' );
});
This is not always desirable. After loading a page, you will see the page flash, but under certain circumstances you have a lot of repeated HTML content, in this case, you can significantly reduce the Page code size and reduce irrelevant and repetitive tags to benefit your SEO.
17. for speed and Seo considerations, there is another way to delay loading content
to speed up page loading and streamline the HTML content searched by spiders, after the page is loaded, use Ajax requests to load other content later, so that users can immediately start browsing and let spider see the content they want to index.
we have used this technology on our website. The purple button in the upper part of this page will pop up three tables with the orientation and Google Map, which will double the page size. Therefore, we only need to put the HTML content into a static page. After the page is loaded, load it using the load () function: copy Code the code is as follows: $ (' # forms '). load ('content/headerforms.html ', function () {
// code here runs once the content has loaded
// put all your event handlers etc. here.
});
I will not use this technique anywhere on the page. You must consider this. You need to have additional page requests, and some content on the page cannot be immediately presented to the user, but correct use of this technique will be helpful for optimization.
18. Use the tool functions provided by jquery
Jquery not only has a flash effect. The author of jquery also provides some practical methods, which fills in some defects of jacascript.
Http://docs.jquery.com/Utilities
In particular, browser support for some common array functions is a patch. Jquery provides methods to iterate, filter, clone, merge, and remove duplicates from arrays.
Other common functions include selecting items in the drop-down list. With the traditional JavaScript method, you must use getelementbyid to get the <SELECT> element, and then traverse its child elements to find the selected element. Jquery provides an easy-to-use method:Copy codeThe Code is as follows: $ ('# selectlist'). Val ();
It is worthwhile to spend time browsing jquery documents on the official website and Some uncommon methods.
19. Use noconflict to rename the jquery object
Most JavaScript frameworks use the $ symbol as the abbreviation. When multiple JS frameworks are used on the same page, the page is prone to conflict. Fortunately, there is a simple method. The noconflict () function returns $ control and allows you to set it to your own variable name:Copy codeThe Code is as follows: $ ('# selectlist'). Val ();
20. How to know that the image has been loaded
This is also a problem that is not well documented (at least I did not see it when searching), but it is quite common in terms of creating a photo repository and rotating lanterns. This is easy to implement in jquery.
All you need to do is to use the. Load () method on IMG and add a callback function in it. The following example changes the property of an image SRC and adds a simple load function to the colleague:Copy codeThe Code is as follows: $ ('# myimag'). ATTR ('src', 'image.jpg'). Load (function (){
Alert ('image loaded ');
});
You should find that an alert will pop up once the image is loaded.
21. Always use the latest version
Jquery is still being updated, and its author John resig has been searching for methods to improve jquery's performance. Jquery's current version is 1.3.2. John has declared that he is writing a new selector engine sizzle, which may significantly improve the selector performance (4 times in Firefox ), therefore, we should keep the latest version.
22. How to check whether the element exists
You don't have to check whether the element exists on the page to use it, because jquery does not do anything if no appropriate element is found in the Dom. However, when we need to check whether the element has been selected or how many items have been selected, you can use the Length attribute:
Copy code The Code is as follows: if ($ ('# mydiv). Length ){
// Your code
}
Simple.
23. Add JS classes to your HTML attributes
I learned this technique from Karl swedberg, and I have been reading his book while learning jquery.
He recentlyArticleI left a comment on this usage. The basic principles are as follows.
First, after jquery is loaded, you can use the method to add the "JS" class to the HTML Tag:Copy codeThe Code is as follows: $ ('html '). addclass ('js ');
This only happens when Javascript is valid. If you enable the Javascript switch, you can use it to add the CSS style to the element:Copy codeThe Code is as follows:. js # mydiv {display: none ;}
Therefore, this means that when Javascript is opened, we can hide the content, and then use jquery to display the content as needed (for example, shrinking or expanding the content when a user clicks ), all content is displayed when JavaScript (and spiders search) is disabled. I will use this technique later.
You can see all his articles here.
24. 'false' is returned to prevent default behavior.
This is obvious, or it may not. If you have the following habits:Copy codeThe Code is as follows: <a href = "#" class = "popup"> click me! </A>
Then add the following event processing:Copy codeThe Code is as follows: $ ('popup'). Click (function (){
// Launch popup code
});
When you use the above method on a long page, it may work normally. Sometimes you will notice that after clicking the link, the anchor will jump to the top of the page.
All you need to do is to stop its default behavior, or you can actually add "Return false;" to the default behavior of any event. Like this:Copy codeThe Code is as follows: $ ('popup'). Click (function (){
// Launch popup code
Return false;
});
25. Short for ready events
You can enter a few characters less than $ (document). Ready.
Replace:
Copy code The Code is as follows: $ (document). Ready (function (){
// Your code
});
You Can abbreviated it to copy Code the code is as follows: $ (function () {
// your code
});