Home >Web Front-end >JS Tutorial >Summary of jQuery code optimization methods

Summary of jQuery code optimization methods

php中世界最好的语言
php中世界最好的语言Original
2018-03-23 09:26:481841browse

This time I will bring you a summary of jQuery code optimization methods. What are the precautions for jQuery code optimization? The following is a practical case, let’s take a look.

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

For example, the following statement has the best performance:

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

When encountering these selectors, jQuery will automatically call the browser's native methods (such as getElementById()), so they execute quickly .

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

To find all hidden elements in a web page, you need to use a pseudo-class selector:

$(':hidden')

An example of an attribute selector is:

$('[attribute=value]')

These two statements are the slowest because the browser has no native method 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, the number of times you use the selector should be as small as possible, and the selected results should be cached as much as possible for repeated use in the future.

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

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

更好的写法是:

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

根据测试,缓存比不缓存,快了2-3倍

jQuery的一大特点,就是允许使用链式写法

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

采用链式写法时,jQuery自动缓存每一步的结果,因此比非链式写法要快。根据测试,链式写法比(不使用缓存的)非链式写法,大约快了25%

事件委托

javascript的事件模型,采用"冒泡"模式,也就是说,子元素的事件会逐级向上"冒泡",成为父元素的事件。

利用这一点,可以大大简化事件的绑定。比如,有一个表格(table元素),里面有100个格子(td元素),现在要求在每个格子上面绑定一个点击事件(click),请问是否需要将下面的命令执行100次?

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

回答是不需要,我们只要把这个事件绑定在table元素上面就可以了,因为td元素发生点击事件之后,这个事件会"冒泡"到父元素table上面,从而被监听到

因此,这个事件只需要在父元素绑定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);
  }

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

javascript的代码优化详解

Node.js的非对称加密详解

360浏览器兼容模式的页面显示不全怎么处理

The above is the detailed content of Summary of jQuery code optimization methods. 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