Simple jquery Starter Guide _jquery

Source: Internet
Author: User
Tags wrapper


Introduction

jquery is one of the most widely used lightweight JavaScript libraries in web development, not only for professional web developers, but also for many novice web developers or Web enthusiasts who are easily integrated into JavaScript by using jquery.

And if you want to do better in this area, you should learn and understand best practices. Best practices are Practice information about the latest technologies and development methodologies that evolve with the development of a technology area and are also useful in web development.

This article refers to the outstanding front-end Engineer Addy Osmani jQuery performance TIPs & Tricks, if you are interested, you can also see this master's Speech yourself Ppt,addy The Osmani self is also a member of the jquery core team (jquery core teams).
Why you need to follow jquery best practices

The pursuit of performance in the field of web development is never stagnant. Although jquery is a very powerful development tool, improper usage still brings additional work and burden to the browser, and makes the development of Web applications more system resources and more slow to run. And we all know that good web apps need to be cool and flexible.

How do you judge the performance of JavaScript? Now, this performance test can be summed up as running speed, simply, the same function, a certain type of writing if more than the other way to run faster, then this method can achieve better performance. Of course, this is only considered from a performance perspective and does not contain the maintainability of the code. If you want to test the performance of different JavaScript code snippets yourself, recommend using jsperf.com, a site that can help you create JavaScript performance test cases easily, and save and share test results. The jquery team also uses it for JavaScript performance testing.
jquery Usage Recommendations
1. Use the latest version

The new version of JQuery provides an API that improves performance and fixes some bugs that exist. Because so many sites are using jquery, changes to each new version of jquery are rigorously tested, and upgrades generally don't cause problems.

In addition, the new version of jquery may make very useful changes to the API to make development work easier. For example, before jquery 1.7, event binding uses bind (), delegate (), and Live () methods. Although they are all event bindings, each method has its own target, which creates the "when to use which" problem. Starting with jquery 1.7, it is much easier to understand that the 2 methods of On () and off () are used to complete all event bindings and removal.
2. Understand your selector

In jquery, not all selectors (selectors) are of equal performance. In other words, although some elements you can use a number of different characters to choose, but do not think they are the same performance.

The jquery selector runs at a different speed, from the fastest to the slowest in turn:

    • ID Selector ($ (#ElementId))
    • Element Selector ($ (form), $ (input), etc.)
    • Class Selector ($ (. SomeClass))
    • Pseudo class and attribute selectors ($ (: Hidden), $ ([attribute=value]), etc.

The ID selector and the element selector are the fastest because the native DOM action methods supported by the browser (such as document.getElementById ()) are available. The slightly slower class selector is because IE6-IE8 does not support native getelementsbyclassname (), and in other modern browsers that support this native method, the class selector is still very fast.

As for the slowest pseudo class and attribute selector, the browser does not provide a usable native method for the corresponding function. Although jquery has tried to elevate the performance of some jquery selectors in some modern browsers using the Queryselector () and Queryselectorall () two native selector APIs (which belong to the CSS query API), it is still relatively slow to combine. Of course, this is also the jquery to the pseudo class and attribute selector This API is higher, not only to support the input[type= "text" of the CSS in the legitimate selector, but also to support p:first this type of element filtering, but in the CSS illegal selectors. In short, jquery's pseudo class and property selector features are powerful, but use it with caution.
3. Caching Elements of your operation

var parents = $ ('. Parents ');
var children = $ ('. Parents '). Find ('. Child '); Bad

Caching is the return result of saving the jquery selector, which is convenient to call again. Each $ ('. whatever ') will again search for and return a jquery wrapper set (jquery collection) from the DOM, so avoid reuse.

In native JavaScript, setting up local variables to cache data or objects helps streamline code and optimize performance. This is the same reason.
4. Chain-type Syntax

var parents = $ ('. Parents '). DoSomething (). Dosomethingelse ();

Most of the methods in jquery return to the jquery wrapper set and support this kind of chained syntax. One of the key points of Javasript performance optimization is to minimize the number of statements, so chained syntax is easier to write and faster to run.
5. Using Event proxies

With event bubbling, you can manage all events of a type by specifying an event handler for an element (such as document) at a higher level of the DOM. Reduces the event handlers added in the page, and naturally improves overall performance.
6. Minimize site Updates

If the DOM part of your operation is part of the page that is already displayed, you are making a live update. field updates require the browser to recalculate the dimensions, involving redrawing (repaint) and Reflow (Reflow), with higher performance costs and therefore less use.

When adding new content, it is recommended that you merge the code snippets that you want to add to the page, and then use a single append () method. And if elements have complex interactions, such as adding and removing them repeatedly, the detach () approach is the best choice.
7. Use the JQuery method when not necessary

$ ('. Nav_link '). Bind (' click ', Function () {
  console.log (' Nav ID: ' + $ (this). attr (' id '));  Bad
$.data (Elem, key, value);  Significantly faster

};

The jquery method is not necessarily the best approach. This uses the $ (this). attr (' id ') to get the ID of the current event element, create a jquery wrapper set for the current event element, and then invoke the attr () property fetch method. But that's all the extra cost of performance. In fact, this represents the current event element within the event function, and the element ID can be obtained directly using This.id, which is written more quickly than the native DOM attribute.
8. Proper use of jquery tool functions

Methods of manipulating the jquery wrapper set (that is, the method written in $.fn), some of which also have similar methods as jquery tool functions (methods written directly in $). Because jquery tool functions do not involve creating jquery wrapper sets in use, in some cases, you can improve performance by swapping jquery tool functions.

For example, to store data in the DOM, it is common practice to:

$ (' #elem '). Data (key, value);  Common Way

But the following wording will be much faster:

Note that although the following method is faster, the elements passed in as arguments cannot be selected with the element itself.
Conclusion

I also feel very rewarding when I organize and write this article myself. jquery is a powerful tool, but further, it only provides the most basic content of web development, more advanced and more complex content, but also need to learn and create. In this process, follow the best practice, develop good habits, there will be great benefits, and gradually do more good!

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.