Home  >  Article  >  Web Front-end  >  A simple guide to getting started with jQuery_jquery

A simple guide to getting started with jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:48:331185browse


Introduction

jQuery can be said to be the most widely used lightweight javascript library in the field of web development. Not only professional web developers use it, but many new web developers or web enthusiasts have also easily integrated into javascript by using jQuery. development.

And if you want to get better at this, you should learn and understand best practices. Best Practice is information about the latest technologies and development methods gradually established with the development of a certain technical field. It is also very useful in the field of web development.

The content of this article refers to the jQuery Performance TIPs & Tricks of the outstanding front-end engineer Addy Osmani. If you are interested, you can also take a look at this master's speech PPT yourself. Addy Osmani himself is also the core team of jQuery (jQuery Core teams) one of the members.
Why you need to follow jQuery best practices

The pursuit of performance in the field of web development will never stop. Although jQuery is a very powerful development tool, improper use will still bring extra work and burden to the browser, and will also cause the developed web application to occupy more system resources and run slower. And we all know that a good web application needs to be fresh and flexible.

How to judge the performance of javascript? Now, this kind of performance test can be summarized as running speed. Simply put, if a certain writing method runs faster than another writing method for the same function, then this writing method can achieve better performance. Of course, this is only considered from a performance perspective and does not include the maintainability of the code. If you want to test the performance of different JavaScript code snippets yourself, it is recommended to use jsPerf.com. This site can help you easily create JavaScript performance test cases, and also save and share test results. The jQuery team also uses it for JavaScript performance testing.
jQuery usage suggestions
1. Use the latest version

The API provided by the new version of jQuery will improve performance and fix some existing bugs. Since many websites are using jQuery, changes to each new version of jQuery will undergo very strict testing, and upgrades generally do not cause problems.

In addition, the new version of jQuery may make very useful changes in the API to make development work easier. For example, before jQuery 1.7, event binding used the bind(), delegate(), and live() methods. Although they are all event bindings, each method has its own purpose, which creates the trouble of "when should I use which one?" Starting from jQuery 1.7, two new methods, on() and off(), are added and recommended to complete all event binding and removal, which makes it much easier to understand.
2. Understand your selectors

In jQuery, not all selectors (Selectors) are equally performant. In other words, although you can select certain elements using many different selector writing methods, don't think that they are also the same in terms of performance.

jQuery’s selectors run at different speeds, from fastest to slowest:

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

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

As for the slowest pseudo-classes and attribute selectors, it is because the browser does not provide available native methods for the corresponding functions. Although jQuery has tried to use querySelector() and querySelectorAll(), two native selector APIs (belonging to the css query API) to improve the performance of some jQuery selectors in some modern browsers, overall they are still relatively slow. Of course, this is also because jQuery has higher API requirements for pseudo-classes and attribute selectors. It must not only support input[type="text"], a legal selector in CSS, but also support p:first for elements. Filter, but is an illegal selector in css. In short, jQuery's pseudo-classes and attribute selectors are very powerful, but please use them with caution.
3. Cache the elements you operate

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

Caching refers to saving the return results of jQuery selectors so that they can be called again later. Each $('.whatever') will re-search the DOM and return a jQuery collection, so reuse is avoided.

In native JavaScript, establishing local variables to cache data or objects is beneficial to streamlining code and optimizing performance. The same principle applies here.
4.Chain syntax

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

jQuery中大部分方法都返回jQuery包装集并支持这种链式语法。javasript的性能优化要点之一是最小化语句数,因此链式语法不仅写起来更容易,运行起来也会更快。
5.使用事件代理

利用事件冒泡,指定一个位于dom较高层级的元素(比如document)的事件处理程序,就可以管理某一类型的所有事件。减少了页面中添加的事件处理程序,自然可以提升整体性能。
6.最小化现场更新

如果你进行操作的DOM部分是已经显示的页面的一部分,那么你就是在进行一个现场更新。现场更新需要浏览器重新计算尺寸,涉及到重绘(repaint)和回流(reflow),有较高的性能花费,因此应减少使用。

在新增内容时,建议先把要新增的代码段合并完全,最后再使用单个append()方法添加到页面。而如果元素存在复杂的交互,比如反复地添加和移除,detach()这个针对性的方法就是最佳的选择。
7.不在不必要的时候使用jQuery方法

$('.nav_link').bind('click', function() {
  console.log('nav id: ' + $(this).attr('id'));  //bad
$.data(elem, key, value);  //significantly faster

};

jQuery方法不一定是最好的方法。这里使用$(this).attr('id')获取当前事件元素的ID,为当前事件元素创建了jQuery包装集,然后调用attr()属性获取方法。但这都是额外的性能花费。事实上,this在事件函数内就表示当前事件元素,直接使用this.id就可以获取元素ID,这种原生DOM属性的写法要更快。
8.适当使用jQuery工具函数

操作jQuery包装集的方法(也就是写在$.fn中的方法),其中一部分也有作为jQuery工具函数(直接写在$中的方法)的同类方法。由于jQuery工具函数在使用中不涉及创建jQuery包装集,因此,在部分情况下,可以通过换用jQuery工具函数提升性能。

比如,在DOM中存储数据,一般的做法是:

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

但改为下边的写法会快很多:

需要的注意的是,虽然下面这种方法更快,但作为参数传入的元素不能用选择符,而要用元素本身。
结语

我自己整理和写本文内容时,也感觉很有收获。jQuery是一个很强大的工具,但进一步说,也只提供了web开发的最基本的内容,更高级更复杂的内容,还需要自己不断学习和创作。在这个过程中,遵循最佳实践,养成良好的习惯,会有很大的益处,并逐渐做得更出色!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn