25 Steps to improve your jquery

Source: Internet
Author: User

1. Load jquery from Google code
Google code already hosts a variety of JavaScript libraries, and loading jquery from Google Code is more advantageous than loading it directly from your server. It saves bandwidth on your server and can quickly load JS class libraries from Google's content distribution network (CDN). More importantly, if a user accesses a site posted on Google Code, it will be cached.
It makes a lot of sense. How many sites use the same jquery copy that is not cached, which is easy to do and introduce:

<script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" ></ Script>

2. Use cheat Sheet
Not only jquery, but also many programming languages have similar cheat sheets, and it's easy to see how each function is used on a A4 piece of paper. Fortunately, there are well-intentioned guys who have made the jquery cheat sheet perfect:
http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
http://colorcharge.com/jquery/

3. Consolidate all the scripts and reduce them
Yes, this is a common technique for JavaScript. However, a large project using jquery may use a lot of related jquery plugins (this site uses easing,localscroll,lightbox,preload), so it is usually applicable. The browser cannot load the JS script at the same time (in most cases), which means that if you load a lot of scripts at the same moment, it slows down the loading of the page. Therefore, if you want to load these scripts for each page, you should consider consolidating them into a slightly larger JS script before publishing. Some jquery plugins have been minimized, but you should pack your JS scripts and those that have not been scaled down, which can be done in a matter of seconds.
Personally, I recommend Packer by Dean Edwards

4. Using Firebug's excellent console logging tool
If you haven't installed Firebug yet, you should really pack it up. In addition to many other useful features (such as allowing you to check HTTP transmissions and discovering your CSS problems), it also has excellent log commands that allow you to easily debug JS scripts.
Here is a detailed description of all the features of Firebug.
My favorite feature is "Console.info", through which you can output information and variable values to the console without using Alert; "Console.time" allows you to set timers on a set of code to calculate the time it takes to run a JS script. It's all easy to do:

Copy the code code as follows:
Console.time (' Create List ');
for (i = 0; i <; i++) {
var myList = $ ('. MyList ');
Mylist.append (' This is List item ' + i);
}
Console.timeend (' Create List ');


5. Minimize selection operation via cache
jquery has a great selection of selectors. They can find any element in a very simple way on the page, but internally they have to go through a number of steps to make the selection, and if you use them wrongly, you may find that everything becomes quite slow.
If you choose the same element over and over again (for example, in a loop), you can select it once and put it into memory, and you can manipulate it in the core content. Look at the example below, where we use loops to add entries to UL:

Copy the code code as follows:
for (i = 0; i <; i++) {
var myList = $ ('. MyList ');
Mylist.append (' This is List item ' + i);
}


It took 1066 milliseconds to Firefox 3 on my PC (imagine the situation in IE6!). ), this is a slow operation for JavaScript. Now let's take a look at the following code, where we use only one selection operation:

Copy the code code as follows:
var myList = $ ('. MyList ');
for (i = 0; i <; i++) {
Mylist.append (' This is List item ' + i);
}


It took only 224 milliseconds to get nearly 4 times times faster by moving a line of code.

6. Minimizing DOM operations
We can make the above code run faster by reducing the insertion of the DOM. The insertion of the DOM (like. Append (),. prepend (),. After (),. Wrap ()) is time-consuming, and performing these actions slows down the program's operation.
All we have to do is use string concatenation to construct a list item and add these items to the list using a function, such as. html (). Take a look at the following example:

Copy the code code as follows:
var myList = $ (' #myList ');
for (i=0; i<1000; i++) {
Mylist.append (' This is List item ' + i);
}


It took 216 milliseconds on my PC, just about 1/5 seconds. But if we construct the list item using a string, the insert operation is done using the following HTML method:

Copy the code code as follows:
var myList = $ ('. MyList ');
var mylistitems = ';
for (i = 0; i <; i++) {
Mylistitems + = ' <li>this is List item ' + i + ' </li> ';
}
Mylist.html (Mylistitems);


It takes 185 milliseconds, although not much faster, but it also increases by 31 milliseconds.
7. Wrapping the required content in one element while processing the DOM insert operation
Well, don't ask me why I'm doing this (I'm sure a programmer with considerable experience will explain it to you).
In the example above, we use. html () to insert 1000 item items into UL. If we wrap these items in a UL tag before inserting, and then insert the full ul into another div tag, then we're actually just inserting a label instead of 1000, which looks more efficient. Take a look at the following example:

Copy the code code as follows:
var myList = $ ('. MyList ');
var mylistitems = ' <ul> ';

for (i = 0; i <; i++) {
Mylistitems + = ' <li>this is List item ' + i + ' </li> ';
}
Mylistitems + = ' </ul> ';
Mylist.html (Mylistitems);


It now takes only 19 milliseconds, a 50 times-fold increase over our first example.
8. Use ID instead of class whenever possible
jquery uses classes for DOM element selection as easily as selecting by ID, so it is attractive to use classes for element selection operations more freely than before. However, because jquery uses the browser's inherent approach (getElementById) for selection, it is more advantageous to use the ID for the selection operation. How fast is it? Let's take a look.
I used the previous example to modify it to make it easy for each li we created to have a unique class. Then I'll traverse it, selecting one element at a time:

Copy the code code as follows:
Create our list
var myList = $ ('. MyList ');
var mylistitems = ' <ul> ';
for (i = 0; i <; i++) {
Mylistitems + = ' <li class= ' listItem ' + i + ' ">this is a list item</li> ';
}
Mylistitems + = ' </ul> ';
Mylist.html (Mylistitems);
Select each item once
for (i = 0; i <; i++) {
var SelectedItem = $ ('. ListItem ' + i);
}


As I thought, my browser took 5066 milliseconds (more than 5 seconds). So I changed the code above to use the ID instead of the class and then select it by ID.

Copy the code code as follows:
Create our list
var myList = $ ('. MyList ');
var mylistitems = ' <ul> ';
for (i = 0; i <; 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 <; i++) {
var SelectedItem = $ (' #listItem ' + i);
}


It takes only 61 milliseconds, almost 100 times times faster.

9. Provide context for selectors
By default, when you use a selector like $ ('. Mydiv '), you'll find elements in the entire DOM document, which is a big cost.
When you perform a selection operation, the jquery function can specify the second parameter: jquery (expression, context) provides a context for the selector, which makes the element lookup in the context without having to find the element in the entire DOM document.
To explain this, we use the first code in the previous section. It creates a UL with 1000 items, each with a separate class.
Then traverse it each time to select one item. You should remember that it takes 5 seconds to select all 1000 items by class.

Copy the code code as follows:
var SelectedItem = $ (' #listItem ' + i);


I then add a context to it so that only the selection can be done in UL:

Copy the code code as follows:
var SelectedItem = $ (' #listItem ' + I, $ ('. MyList '));


Because of the poor efficiency, it still takes 3818 milliseconds, but with a small modification, it still gets a 25% increase in speed.
10. Proper use of the method chain
One of the most dazzling features of jquery is that jquery is able to make successive method calls. For example, you want to switch the class of the element:

Copy the code code as follows:
$ (' mydiv '). Removeclass (' off '). addclass (' on ');


If you're like me, you might be able to use it further in the first five minutes of jquery learning. First it can still cross-line (jquery is JavaScript), which means you can write a neat code like this:

Copy the code code as follows:
$ (' #mypanel ')
. Find (' TABLE. Firstcol ')
. Removeclass ('. Firstcol ')
. css (' background ': ' Red ')
. Append (' <span>this cell is now red</span> ');


The habit of using linked lists will help you reduce the use of selectors. However, you can use it more deeply, you want to perform several functions on an element, but change the elements of the operation in some way:

Copy the code code as follows:
$ (' #myTable '). Find ('. Firstcolumn '). CSS (' background ', ' red ');


We chose a table where we found the cell with the class "Firstcolumn" and then turned the background red.
Now we want to set all the cell backgrounds of class "Lastcolumn" to blue. Because we have used the find () function to filter out all the cells of class that are not "firstcolumn", so we need to use the selection operation again for the table, can't we make successive method calls? Fortunately, jquery provides the end () function, which changes the list of matching elements to the previous state so that you can execute the method chain table:

Copy the code code as follows:
$ (' #myTable ')
. Find ('. Firstcolumn ')
. css (' background ', ' red ')
. End ()
. Find ('. Lastcolumn ')
. css (' background ', ' blue ');


It's also easy to write a custom jquery function that makes a method-chained call. All you have to do is write a function that modifies the element and returns the element.

Copy the code code as follows:
$.fn.makered = function () {
return $ (this). CSS (' background ', ' red ');
}
$ (' #myTable '). Find ('. Firstcolumn '). makered (). Append (' Hello ');


It's very simple!

11. Learn to use the effect correctly
When I first started using jquery, I liked the fact that it was easy to use predefined animation effects like Slidedown () and Fadein (). Because the animate () method provided by jquery is very easy to use and powerful, it is easy to drill down into. In fact, many of the methods in the jquery source code are implemented using the animate () function.

Copy the code code 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 works only on the CSS, and is converted according to the numerical smoothing. So you can change the width, height, transparency, background color, top, left, margin, color, font size, and whatever you want.
Adding a highly variable effect to a menu item is easy to do:

Copy the code code as follows:
$ (' #myList Li '). MouseOver (function () {
$ (this). Animate ({"height": +), "slow");
});


Unlike other jquery functions, animations automatically queue up, so if you want to run a second effect after the first effect is complete, you need to call the Animate method two times:

Copy the code code as follows:
$ (' #myBox '). MouseOver (function () {
$ (this). Animate ({"width": $, "slow");
$ (this). Animate ({"Height": $, "slow");
});


If you want the animation to happen at the same time, you need to pass all styles as a parameter object into the method:

Copy the code code as follows:
$ (' #myBox '). MouseOver (function () {
$ (this). Animate ({"width": $, "height": $}, "slow");
});


You can animate a property that has a numeric value. You can also download plugins to help you animate non-numeric properties like colors and background colors

12. Understanding Event Proxies
jquery makes it easier to add events seamlessly to DOM elements than before. This is a great feature, but adding too many events to an element is inefficient. In many cases, the event broker allows you to achieve the same purpose with a small number of events. The best way to explain this is to use an instance:

Copy the code code as follows:
$ (' #myTable TD '). Click (function () {
$ (this). CSS (' background ', ' red ');
});


When we click on a cell in the table, the above code will turn all the cell backgrounds to red. For example, if you have a grid of 10 columns and 50 rows, you will bind 500 events. Well, this is the time for the event agent to appear:

Copy the code code as follows:
$ (' #myTable '). Click (function (e) {
var clicked = $ (E.target);
Clicked.css (' Background ', ' red ');
});


E ' contains information about the event, including the target element that actually received the Click event. All we have to do is check which cell is clicked. Quite ingenious!
The event broker brings another benefit. Normally, when you bind an event to an element collection, the event is simply bound to those collection elements. If you add new elements to the DOM, although these new elements are matched by selectors, these new elements are not bound to event handling (do you agree with me?). ), so no events occur.
When using the event proxy, you can still add multiple matched elements to the event after it has been bound by the DOM, and they will work as expected.
13. Using Classes Storage status
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 the state information for an element, why not try using an extra class to store it?
Here's an example. We want to create an expanded menu. When you click on the button, we want to expand and contract the menu through Slidedown () and Slideup (). Take a look at the following HTML:

Copy the code code as follows:
<div class= "MenuItem expanded" >
<div class= "button" >
Click Me
</div>
<div class= "Panel" >
<ul>
<li>menu Item 1</li>
<li>menu Item 2</li>
<li>menu Item 3</li>
</ul>
</div>
</div>


It's very simple! We just add an extra class to the wrapper div and it just tells us the state of the item item. So all we need after the button click is the Click event handler, which executes the corresponding slideup () and Slidedown () methods.

Copy the code code as follows:
$ ('. 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 an extra classes to an element or HTML fragment to store all kinds of information.
However, we should use the following technique in addition to the simple case.
14. A better approach is to use the jquery built-in data () method to store the state
For some reason, this is not a good document to refer to. jquery provides the built-in data () method, which, unlike DOM elements, can be used to store key/value types. The storage of the data is very easy:

Copy the code code as follows:
$ (' #myDiv '). Data (' CurrentState ', ' off ');


We modify the code of the previous example so that we can use the same HTML content (except for the "expanded" class) and use the data () function to store the state:

Copy the code code as follows:
$ ('. 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'm sure you'll agree that the use of this method is indeed more subtle, for more information on data () and Removedata (), see jquery internals
15. Write your own selector
jquery has a number of built-in selectors for selecting operations through ID, class, tag, attributes, and other elements. But what can you do when you need to select elements based on other content and jquery does not provide the selector?
Well, one solution might be to add a classes to an element from the beginning, and take advantage of these classes to make the element selection operation. However this proved difficult to extend the new selector to jquery.
The best way to explain this is to use an instance:

Copy the code code as follows:
$.extend ($.expr[': '), {
Over100pixels:function (a) {
Return $ (a). Height () > 100;
}
});

$ ('. Box:over100pixels '). Click (function () {
Alert (' The element you clicked are over-pixels high ');
});


The first part of the code creates a custom selector that finds all elements that are longer than 100px. The next code simply binds the click event to those elements found using the selector.
I don't do a more specific explanation here, but you can imagine how powerful it is! If you search for "custom jquery selector" on Google, you'll see a lot of examples of this.

16. Refine your HTML and modify it after the page is loaded
This title may not mean much, but this technique might straighten out your code, reduce the size of your code and download time on your page, and help optimize your search engine. Take a look at the following example:

Copy the code code 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>


Above is a specific example of HTML, for the purpose of explaining a few modifications. I'm sure you'll think this code is pretty ugly. If the code is long, you'll end up with a fairly long and ugly page. So you can handle it like this:

Copy the code code 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 have to do is add the ugly HTML back with jquery after the page is loaded:

Copy the code code as follows:
$ (document). Ready (function () {
$ ('. field '). Before (' <div class= "Fieldouter" ><div class= "inner" > ");
$ ('. field '). After (' </div><div class= "ErrorBar" ><div class= "icon" >
</div><div class= "message" >
<span>this is an error message</span></div></div></div> ');
});


This is not always desirable, in the moment after the page load you will see the page flashing, but in certain circumstances you have a lot of duplicate HTML content, this way you can significantly reduce the page code volume, reduce irrelevant and duplicate tags can make your SEO benefit from.
17. Delay loading content for speed and SEO considerations
There is also a way to speed up the page load, straighten out the HTML content of the Spiders search, and load the other content later using AJAX requests after the page loads, so that the user can start browsing right away and let the spider see what you want them to index.
We have already used this technology on our website. The purple button at the top of this page will pop up three tables, with Google Maps, which will add twice times the size of our page. So we just need to put the HTML content in a static page and load it through the load () function after the page is loaded:

Copy the code code as follows:
$ (' #forms '). Load (' content/headerforms.html ', function () {
Code here runs once the content have loaded
Put all your event handlers etc.
});


I won't use this technique anywhere on the page. For this, you must weigh the considerations. You need to have additional page requests, and some of the content on the page is not immediately available to the user, but the correct use of this technique can be helpful for optimization.
18. Using the tool functions provided by jquery
jquery is not just a flash effect. The jquery author also offers some fairly practical ways to fill some of the flaws in Jacascript.
Http://docs.jquery.com/Utilities
In particular, providing browser support for some common array functions is a patch. jquery provides a way 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 the traditional JavaScript method, you have to use getElementById to get the <select> element and then find the selected element by traversing its child elements. And jquery offers a fairly easy-to-use approach:

Copy the code as follows: $ (' #selectList '). Val ();


It is worthwhile to spend time browsing the jquery documents on the official website and some of the less commonly used methods.
19. Using Noconflict to rename a jquery object
Most JavaScript frameworks use the $ symbol as an abbreviation, and when multiple JS frames are used on the same page, the page is prone to conflict. Fortunately, there is an easy way. The Noconflict () function returns the control of $ and allows you to set your own variable name:

Copy the code code as follows:
$ (' #selectList '). Val ();


20. How to know that the picture has been loaded
This is also an issue with no good documentation (at least not seen when I'm looking), but it is a fairly common requirement for creating photo galleries, rotating lantern effects, and so on. And that's easy to achieve in jquery.
All you have to do is use the. Load () method on the IMG to add a callback function to it. The following example changes the properties of a picture src to a colleague attaching a simple load function:

Copy the code code as follows:
$ (' #myImage '). attr (' src ', ' image.jpg '). Load (function () {
Alert (' Image Loaded ');
});


You should be able to see that once the picture is loaded, an alert pops up.
21. Always use the latest version
jquery is still constantly being updated, and its author, John Resig, has been looking for ways to improve the performance of jquery. The current version of jquery is 1.3.2,john has claimed that he is writing a new selector engine sizzle, which could significantly improve selector performance (4 times times faster in Firefox), so we should keep the latest version.

22. How to check if an element exists
You don't have to check if an element exists on the page to use it, because jquery doesn't do anything without finding the right element in the DOM. But when we need to check whether the element is selected, or how many items are selected, you can use the Length property:

Copy the code code as follows:
if ($ (' #myDiv). Length) {
Your code
}


Simple.
23. Add JS class to your HTML attributes
I learned this trick from Karl Swedberg, who used to read his book while studying jquery.
He recently left a comment on the usage in my previous article, the Basic principles are as follows.
First, after the jquery is loaded, you can use the method to add the "JS" class to the HTML tag:

Copy the code code as follows: $ (' HTML '). addclass (' JS ');


Because this only happens when JavaScript is in effect, if the user opens the JavaScript switch, you can use it to add CSS style to the element:

Copy the code code as follows:. JS #myDiv {display:none;}



So, this means that we can hide the content when JavaScript is open, and then use jquery to display the content when it is needed (such as shrinking or expanding the content when the user clicks it), while closing JavaScript (and searching for spiders) to see everything. I will use this technique at a later time.
You can see all of his articles here.
24. Return ' false ' to prevent default behavior
This is obvious, or it may not be. If you have such a habit:

Copy the code code as follows:
<a href= "#" class= "popup" >click me!</a>


Then add the following event handling:

Copy the code code as follows:
$ (' popup '). Click (function () {
Launch Popup Code
});



When you use the above method on a long page, it may work correctly. There are times when you notice that the anchor point jumps to the top of the page after clicking the link.
All you have to do is stop the default behavior of it, or you can actually put "return false;" Added to the default behavior of any event. Like this:

Copy the code code as follows:
$ (' popup '). Click (function () {
Launch Popup Code
return false;
});

Shorthand for the Ready event
A little trick but by using the shorthand for the $ (document). Ready (), you can enter a few characters less.
Replace:

Copy the code code as follows:
$ (document). Ready (function () {
Your code
});


You can write in Jane:

Copy the code code as follows:
$ (function () {
Your code
});

25 Steps to improve your jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.