[Translation] 25 tips to improve your jQuery-[1]

Source: Internet
Author: User

Address: http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

Preface
JQuery is amazing. I have been using it for more than a year. The longer I use it, the more I understand its internal operations.

I am not a jQuery expert. I do not claim to be myself. Therefore, if you find any errors in the following articles, please correct them or make suggestions for improvement at any time.

I call myself an intermediate jQuery user. I think others may benefit from the tips, tricks, and methods I 've learned over the past year. This article is a little longer than I originally imagined. Therefore, I provided a directory at the beginning. You can jump to the interesting part to read it.

Directory

1. Load jQuery from Google Code
2. Use the memo form
3. Integrate all scripts and reduce them
4. Use Firebug's excellent console logging tool
5. Minimize selection through caching
6. Minimize DOM operations
7. Wrap the required content in an element when processing DOM insert operations
8. Try to use IDs instead of classes
9. provide context for the selector
10. Use method chain correctly
11. Learn to use results correctly
12. Understand event proxy
13. Use classes to store the status
14. A better way is to store the status using the built-in data () method of jQuery.
15. Write your own Selector
16. Streamline your HTML and modify it after loading the page
17. Delayed loading of content for speed and SEO considerations
18. Use the tool functions provided by jQuery
19. Use noConflict to rename the jQuery object
20. How to know that the image has been loaded
21. Always use the latest version
22. How to check whether the element exists
23. Add JS classes to your HTML attributes
24. 'false' is returned to prevent default behavior.
25. Short for ready events

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. It saves the 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 published on Google Code, it will be cached.

This is meaningful. How many sites use the same jQuery copy that has not been cached, which is easy to do:

<script src="http://www.google.com/jsapi"></script>   <script type="text/javascript">       // Load jQuery      google.load("jquery", "1.2.6");       google.setOnLoadCallback(function() {          // Your code goes here.      });             </script>  

Alternatively, you can directly reference JS:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

Here are detailed usage instructions

2. Use the memo form
Not only jQuery, but many programming languages also have similar memos. On an A4 paper, you can easily see the usage of each function. 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/

[Note]

JQuery 1.3 Cheat Sheet

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". You can use it to output information and variable values to the console without using alert; "console. time "allows you to set a timer on a set of code to calculate the time it takes to run the JS script. It is easy to do this:

console.time('create list');     for (i = 0; i < 1000; i++) {       var myList = $('.myList');       myList.append('This is list item ' + i);   }     console.timeEnd('create list');

In this example, I intentionally wrote some inefficient code! In the following tips, I will show you how to use a timer to display our improvements to JS Code.

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:

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:

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. append (),. prepend (),. after (),. wrap () is quite time-consuming. executing these operations will slow down the running of the 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:

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:

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:

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 time spent is only 19 ms, which is obviously 50 times higher than the previous example.

8. Try to use IDs instead of classes
JQuery uses classes for DOM element selection, which is as easy as selecting by 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:

var myList = $('.myList');   var myListItems = '<ul>';    for (i = 0; i < 1000; 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 < 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.

// 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 selecting an operation, the jQuery function can specify the second parameter:
JQuery (expression, context)

By providing a context for the selector, the element search will be performed in this context, instead of searching for the element 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.

var selectedItem = $('#listItem' + i);

Then I add a context for it to perform the selection operation in UL only:

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:

$('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:

$('#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:

$('#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 out 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:

$('#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.

$.fn.makeRed = function() {       return $(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 fact, many methods in jQuery source code are implemented 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 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:

$('#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:

$('#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:

$('#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:

$('#myTable TD').click(function(){       $(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:

$('#myTable').click(function(e) {       var clicked = $(e.target);       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 the status
This is the most basic way to store 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:

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

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.

$('.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 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:

$('#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:

$('.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 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:

$.extend($.expr[':'], {       over100pixels: function(a) {           return $(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.

 

[Note]

Because the article is too long, I plan to translate it twice. The remaining chapters will be supplemented later. Please wait!

See next article: http://www.cnblogs.com/huyh/archive/2009/03/31/1425430.html

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.