Simple jQuery Getting Started Guide _ jquery-js tutorial

Source: Internet
Author: User
This article mainly introduces the simple jQuery Getting Started Guide. jQuery is the most popular JavaScript library today. For more information, see Introduction

JQuery is the most widely used lightweight javascript library in the web development field. It is not only used by professional web developers, many beginners web developers or web enthusiasts can easily integrate javascript development with jQuery.

If you want to do better in this area, you should learn and understand the best practices. Best Practice is a piece of information about the latest technologies and development methods gradually established with the development of a certain technical field, which is also very useful in the web development field.

This article references the jQuery Performance TIPs & Tricks of Addy Osmani, an outstanding front-end engineer. If you are interested, you can also take a look at this master's speech PPT, addy Osmani is also a member of jQuery Core teams.
Why do we need to follow jQuery best practices?

The pursuit of performance in the web development field never stops. Although jQuery is a very powerful development tool, improper use of jQuery will bring additional work and burden to the browser, and make the developed web application occupy more system resources, it is also slower to run. As we all know, good web applications require refreshing and flexibility.

How can we determine the performance of javascript? Now, this kind of performance test can be summarized as running speed. Simply put, if one function runs faster than another, this method can achieve better performance. Of course, here we only consider performance, and do not include the maintainability of the Code. If you want to test the performance of different javascript code segments by yourself, jsPerf.com is recommended. This site can help you easily create javascript performance test cases and save and share test results. The jQuery team also uses it for javascript performance testing.
JQuery recommendations
1. Use the latest version

The new version of jQuery provides improved performance and fixes some bugs. Since jQuery is used by many websites, every new version of jQuery will undergo very strict tests and upgrades will not cause problems.

In addition, the new version of jQuery may make very useful changes on the API, making development easier. For example, before jQuery 1.7, bind (), delegate (), and live () are used for event binding. Although all events are bound, each method has its own purpose, which leads to the annoyance of "when should I use. Since jQuery 1.7, we have added and recommended the on () and off () Methods to bind and remove all events, which is much easier to understand.
2. Understand your Selector

In jQuery, not all Selectors have the same performance. That is to say, although some elements can be selected using many different selection operators, do not think they are the same in terms of performance.

The speed of jQuery selection varies, from the fastest to the slowest:

  • ID selector ($ (# ElementId ))
  • Element selector ($ (form), $ (input), etc)
  • Class selector ($ (. someClass ))
  • Pseudo class and attribute selector ($ (: hidden), $ ([attribute = value)

Because the native DOM operation methods supported by the browser (such as document. getElementById () are available, the ID and element selector are the fastest. The slow Class selector is because the 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, it is because the browser does not provide the native method available for the corresponding function. Although jQuery tries to use the querySelector () and querySelectorAll () Native selector APIs (which are css query APIs) to improve the performance of some jQuery selector in some modern browsers, however, in combination, it is still relatively slow. Of course, this is because jQuery has high requirements on the API of pseudo-class and attribute selector. It must not only support valid selector in css such as input [type = "text, the p: first type is also supported for element filtering, but it is invalid in css. In short, jQuery's pseudo class and attribute selector functions are powerful, but please use them with caution.
3. cache the elements you operate on

var parents = $('.parents');var children = $('.parents').find('.child'); //bad

Cache is used to save the returned results of the jQuery selector and then call it again. Every $ ('. whatever') will re-search from the DOM and return a jQuery collection, so avoid repeated use.

In Native javascript, setting up local variables to cache data or objects helps streamline code and optimize performance. The same is true here.
4. Chain syntax

var parents = $('.parents').doSomething().doSomethingElse();

Most of jQuery's methods return jQuery's packaging set and support this chained syntax. One of the key points to optimize the performance of javasript is to minimize the number of statements. Therefore, the chain syntax is easier to write and faster to run.
5. Use event proxy

With event bubbling, you can manage all types of events by specifying an event handler that is at a higher level of dom elements (such as document. Reduces the number of Event Handlers added to the page, which can naturally improve overall performance.
6. Minimize on-site updates

If the DOM part of your operation is a part of the displayed page, you are performing an on-site update. On-site update requires the browser to re-calculate the size, involving repainting and reflow, with high performance costs and therefore should be reduced.

When adding new content, we recommend that you merge the code segments to be added completely, and then add them to the page using a single append () method. If the elements have complex interactions, such as repeated addition and removal, the targeted method of detach () is the best choice.
7. Do not use the jQuery method when necessary

$('.nav_link').bind('click', function() {  console.log('nav id: ' + $(this).attr('id'));  //bad

$.data(elem, key, value);  //significantly faster

};

JQuery is not necessarily the best method. Here, $ (this). attr ('id') is used to obtain the id of the current event element, create a jQuery package set for the current event element, and then call the attr () attribute to obtain the method. However, this is an additional performance cost. In fact, this indicates the current event element in the event function. You can use this. id directly to obtain the element ID. this native DOM attribute can be written faster.
8. Use jQuery tool functions as appropriate

The method used to operate the jQuery package set (that is, the method written in $. fn). Some of them also have similar methods as jQuery tool functions (directly written in $. Because jQuery tool functions do not involve creating jQuery packaging sets, you can use jQuery tool functions to improve performance in some cases.

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

$('#elem').data(key, value);  //common way

But the writing method below will be much faster:

It should be noted that, although the following method is faster, the elements passed in as parameters cannot use the selector, but must use the element itself.
Conclusion

I also feel very rewarding when I organize and write my own content in this article. JQuery is a powerful tool, but further speaking, it only provides the most basic content for web development. More advanced and complex content also needs to be learned and created by yourself. In this process, it will be of great benefit to follow the best practices and develop good habits, and gradually become better!

Related Article

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.