Home  >  Article  >  Web Front-end  >  Detailed instructions on code optimization in jQuery

Detailed instructions on code optimization in jQuery

亚连
亚连Original
2018-06-09 10:46:241213browse

This article summarizes jQuery code optimization methods for everyone. If you have needs in this area, let’s learn together.

Use the right selector

In jQuery, you can use multiple selectors to select the same web page element. The performance of each selector is different, and you should understand their performance differences

1. The fastest selector: id selector and element label selector

For example, the following The statement performance is the best:

$('#id')
$('form')
$('input')

When encountering these selectors, jQuery will automatically call the browser's native methods (such as getElementById()), so their execution speed is fast.

2. Slower selector: The performance of class selector

$('.className') depends on different browsers. Firefox, Safari, Chrome, and Opera browsers all have native methods getElementByClassName(), so the speed is not slow. However, IE5-IE8 have not deployed this method, so this selector will be quite slow in IE

3. The slowest selector: pseudo-class selector and attribute selector

Find To remove all hidden elements in a web page, a pseudo-class selector must be used:

$(':hidden')

An example of an attribute selector is:

$('[attribute=value]')

These two statements are the slowest, because browsing There are no native methods for them. However, some new versions of browsers have added querySelector() and querySelectorAll() methods, which will greatly improve the performance of this type of selector

Understanding the parent-child relationship

The following six Selectors all select child elements from parent elements

$('.child', $parent)
$parent.find('.child')
$parent.children('.child')
$('#parent > .child')
$('#parent .child')
$('.child', $('#parent'))

1. The following statement means that given a DOM object, then select a child element from it. jQuery will automatically convert this statement into $.parent.find('child'), which will cause a certain performance loss. It is 5%-10% slower than the fastest form

$('.child', $parent)

2. This is the fastest statement. The .find() method will call the browser's native methods (getElementById, getElementByName, getElementByTagName, etc.), so it is faster

$parent.find('.child')

3. This statement will use $.sibling() and JavaScript's nextSibling() method traverses nodes one by one. It is about 50% slower than the fastest form

$parent.children('.child')

4. jQuery uses the Sizzle engine internally to handle various selectors. The selection order of the Sizzle engine is from right to left, so this statement selects .child first, and then filters out the parent element #parent one by one, which causes it to be about 70% slower than the fastest form

$('#parent > .child')

5. This statement is the same as the previous one. However, the previous one only selects direct sub-elements, while this one can select multi-level sub-elements, so it is slower, about 77% slower than the fastest form

$('#parent .child')

6. jQuery will internally This statement is converted to $('#parent').find('.child'), which is 23% slower than the fastest form

$('.child', $('#parent'))

So, the best choice is $parent.find('. child'). Moreover, since $parent is often generated in the previous operation, jQuery will cache it, thus further speeding up the execution speed

Do not overuse jQuery

No matter how fast jQuery is, it cannot compete with the native compared to javascript methods. Therefore, when there are native methods that can be used, try to avoid using jQuery.

Taking the simplest selector as an example, document.getElementById("foo") is more than 10 times faster than $("#foo")

Let's look at another example, for the a element Bind a function that handles click events:

$('a').click(function(){
    alert($(this).attr('id'));
  });

This code means that after clicking on an element, the id attribute of the element will pop up. In order to obtain this attribute, jQuery must be called twice in succession, the first is $(this), and the second is attr('id').

In fact, this processing is completely unnecessary. The more correct way to write it is to directly use the native JavaScript method to call this.id:

$('a').click(function(){
    alert(this.id);
  });

According to tests, the speed of this.id is more than 20 times faster than $(this).attr('id')

Cache well

Selecting a certain web page element is a very expensive step. Therefore, you should use the selector as few times as possible, and cache the selected results as much as possible for repeated use in the future.

For example, the following way of writing is a bad way of writing:

jQuery('#top').find('p.classA');
jQuery('#top').find('p.classB');

A better way of writing is:

var cached = jQuery('#top');
  cached.find('p.classA');
  cached.find('p.classB');

According to the test, caching is 2-3 times faster than not caching. Times

One of the major features of jQuery is that it allows the use of chain writing.

$('p').find('h3').eq(2).html('Hello');

When chain writing is used, jQuery automatically caches the results of each step, so it is faster than non-chain writing. According to tests, the chain writing method is about 25% faster than the non-chain writing method (without caching)

Event delegation

Javascript's event model adopts the "bubble" mode, which is That is to say, events on child elements will "bubble" up one level and become events on the parent element.

Using this, event binding can be greatly simplified. For example, there is a table (table element) with 100 cells (td element) in it. Now it is required to bind a click event (click) to each cell. Do you need to execute the following command 100 times?

$("td").on("click", function(){
    $(this).toggleClass("click");
  });

The answer is no, we only need to bind this event to the table element, because after a click event occurs on the td element, this event will "bubble" to the parent element table, thereby being Listen to

因此,这个事件只需要在父元素绑定1次即可,而不需要在子元素上绑定100次,从而大大提高性能。这就叫事件的"委托处理",也就是子元素"委托"父元素处理这个事件

$("table").on("click", "td", function(){
    $(this).toggleClass("click");
  });

更好的写法,则是把事件绑定在document对象上面

$(document).on("click", "td", function(){
    $(this).toggleClass("click");
  });

如果要取消事件的绑定,就使用off()方法

$(document).off("click", "td");

少改动DOM

1、改动DOM结构开销很大,因此不要频繁使用.append()、.insertBefore()和.insetAfter()这样的方法

如果要插入多个元素,就先把它们合并,然后再一次性插入。根据测试,合并插入比不合并插入,快了将近10倍

2、如果要对一个DOM元素进行大量处理,应该先用.detach()方法,把这个元素从DOM中取出来,处理完毕以后,再重新插回文档。根据测试,使用.detach()方法比不使用时,快了60%

3、如果要在DOM元素上储存数据,不要写成下面这样:

var elem = $('#elem');
elem.data(key,value);

而要写成

var elem = $('#elem');
$.data(elem[0],key,value);

根据测试,后一种写法要比前一种写法,快了将近10倍。因为elem.data()方法是定义在jQuery函数的prototype对象上面的,而$.data()方法是定义jQuery函数上面的,调用的时候不从复杂的jQuery对象上调用,所以速度快得多

4、插入html代码的时候,浏览器原生的innterHTML()方法比jQuery对象的html()更快

尽量少生成jQuery对象

每当使用一次选择器(比如$('#id')),就会生成一个jQuery对象。jQuery对象是一个很庞大的对象,带有很多属性和方法,会占用不少资源。所以,尽量少生成jQuery对象

举例来说,许多jQuery方法都有两个版本,一个是供jQuery对象使用的版本,另一个是供jQuery函数使用的版本。下面两个例子,都是取出一个元素的文本,使用的都是text()方法

既可以使用针对jQuery对象的版本:

var $text = $("#text");
var $ts = $text.text();

也可以使用针对jQuery函数的版本:

var $text = $("#text");
var $ts = $.text($text);

由于后一种针对jQuery函数的版本不通过jQuery对象操作,所以相对开销较小,速度比较快

选择作用域链最短的方法

严格地说,这一条原则对所有Javascript编程都适用,而不仅仅针对jQuery

我们知道,Javascript的变量采用链式作用域。读取变量的时候,先在当前作用域寻找该变量,如果找不到,就前往上一层的作用域寻找该变量。这样的设计,使得读取局部变量比读取全局变量快得多

请看下面两段代码,第一段代码是读取全局变量:

var a = 0;
  function x(){
    a += 1;
  }

第二段代码是读取局部变量:

function y(){
    var a = 0;
    a += 1;
  }

第二段代码读取变量a的时候,不用前往上一层作用域,所以要比第一段代码快五六倍

同理,在调用对象方法的时候,closure模式要比prototype模式更快

prototype模式:

var X = function(name){ this.name = name; }
X.prototype.get_name = function() { return this.name; };

closure模式:

var Y = function(name) {
    var y = { name: name };
    return { 'get_name': function() { return y.name; } };
  };

同样是get_name()方法,closure模式更快

使用Pub/Sub模式管理事件

当发生某个事件后,如果要连续执行多个操作,最好不要写成下面这样:

function doSomthing{
    doSomethingElse();
    doOneMoreThing();
  }

而要改用事件触发的形式:

function doSomething{
    $.trigger("DO_SOMETHING_DONE");
  }
  $(document).on("DO_SOMETHING_DONE", function(){
    doSomethingElse(); 
  });

还可以考虑使用deferred对象

function doSomething(){
    var dfd = new $.Deferred();
    //Do something async, then... 
    //dfd.resolve();
    return dfd.promise();
  }
  function doSomethingElse(){
    $.when(doSomething()).then(//The next thing);
  }

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在微信小程序中如何使用switch开关选择器

在JavaScript中如何计算多边形质心

在Angular19中有关自定义表单控件使用

The above is the detailed content of Detailed instructions on code optimization in jQuery. For more information, please follow other related articles on the PHP Chinese website!

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