jQuery 优化/最佳实践

发布于 2024-09-09 06:49:49 字数 1845 浏览 4 评论 0 原文

好吧,给牛仔们准备好马鞍,因为这将是一场漫长的比赛。我花了一个早上的时间检查一些旧代码,我想知道最佳实践和优化。为了避免走上主观路线,我将只发布一些示例,其中一些希望很容易回答问题。我将尽量使示例保持简单,以便于回答并减少出错的可能性。我们开始吧:

1) 赋值与 jQuery 调用

我知道,当访问选择器时,通常认为将选择器分配给变量比多次进行相同的调用更好 - 例如。

$('div#apples').hide();
$('div#apples').show();

vs.

var oranges = $('div#oranges');
oranges.show();
oranges.hide();

引用 jQuery 的 $(this) 时是否适用相同的规则?前任。一个简单的脚本,使表中的某些数据可单击并自定义链接。

$('tr td').each( function() {
    var colNum = $(this).index();
    var rowNum = $(this).parent().index();
    $(this).wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
})

vs.

$('tr td').each( function() {
    var self = $(this);
    var colNum = self.index()
    var rowNum = self.parent().index()
    self.wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
});

2) this vs $(this)

好吧,下一个是我想了很长时间的东西,但我似乎找不到任何信息在它上面。请原谅我的无知。什么时候调用普通 js this 而不是 jQuery 包装的 $(this) 才有意义?据我理解 -

$('button').click(function() {
  alert('Button clicked: ' + $(this).attr('id'));
});

效率比访问普通 this 对象的 DOM 属性,如下所示 -

$('button').click(function() {
  alert('Button clicked: ' + this.id);
});

我明白那里发生了什么,我只是想知道在决定使用哪个时是否有经验法则可以遵循。

3)特异性越高越好吗?

这个非常简单,对我们的选择器更加具体总是有益的吗?很容易看出 $('.rowStripeClass') 会比 $('#tableDiv.rowStripeClass') 慢得多,但是我们在哪里划清界限呢? $('body div#tableDiv table tbody tr.rowStripeClass') 还更快吗?任何意见将不胜感激!

如果您已经看到这里,感谢您的阅读!如果你还没有,:p

Ok saddle up cowboys, because this is going to be a long one. I have been spending the morning going through some of my old code and I'm left wondering about best practices and optimzation. In order to avoid a ride down subjective lane I'll just post some examples with some hopefully easy to answer questions. I will try to keep the examples very simple for ease of an answer and to decrease the likelihood of mistakes. Here we go:

1) Assignment vs jQuery Calls

I understand that when accessing selectors it's generally considered better to assign a selector to a variable rather than make the same call more than once - ex.

$('div#apples').hide();
$('div#apples').show();

vs.

var oranges = $('div#oranges');
oranges.show();
oranges.hide();

Does this same rule apply when referencing jQuery's $(this)? Ex. A simple bit of script to make some data in a table clickable and customize the link.

$('tr td').each( function() {
    var colNum = $(this).index();
    var rowNum = $(this).parent().index();
    $(this).wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
})

vs.

$('tr td').each( function() {
    var self = $(this);
    var colNum = self.index()
    var rowNum = self.parent().index()
    self.wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
});

2) this vs $(this)

Ok so this next one is something that I have wondered about for a long time but I can't seem to find any information on it. Please excuse my ignorance. When does it make sense to call the vanilla js this as opposed to the jQuery wrapped $(this)? It's my understanding that -

$('button').click(function() {
  alert('Button clicked: ' + $(this).attr('id'));
});

Is much less efficient than accessing the DOM attribute of the vanilla this object like the following -

$('button').click(function() {
  alert('Button clicked: ' + this.id);
});

I understand what is going on there, Im just wondering if there is a rule of thumb to follow when deciding which to use.

3) Is more specificity always better?

This one is pretty simple, is it ALWAYS beneficial to be more specific with our selectors? It's easy to see that $('.rowStripeClass') would be much slower than $('#tableDiv.rowStripeClass'), but where do we draw the line? Is $('body div#tableDiv table tbody tr.rowStripeClass') faster still? Any input would be appreciated!

If you've made it this far, thanks for taking a look! If you haven't, :p

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

貪欢 2024-09-16 06:49:49

我将尝试尽可能简洁地回答这些问题:

  1. 在经常使用时缓存它,尤其是在循环情况下,运行相同代码来获取< em>相同结果对性能来说从来都不是一件好事,缓存它。

  2. 当你只需要一个 DOM 元素时使用 this ,当你需要 $(this) rel="noreferrer">jQuery 方法(否则不可用),您的 this.id$(this).attr("id" 示例) 很完美,一些更常见的例子:

    • 使用 this.checked 而不是 $(this).is(':checked')
    • 使用 $.data(this, 'thing') 代替 $(this).data('thing')
    • 创建 jQuery 对象基本上没有用的任何其他情况。
  3. 为了性能,从 ID 选择器降序是首选...您需要具体到什么程度?简而言之,这完全取决于:按照您需要的具体程度

I'll try to answer these as concisely as possible:

  1. Cache it when it's used often, especially in a loop situation, running the same code to get the same result is never a good thing for performance, cache it.

  2. Use this when you only need a DOM element and $(this) when you need the jQuery methods (that wouldn't be available otherwise), your example of this.id vs $(this).attr("id") is perfect, some more common examples:

    • Use this.checked instead of $(this).is(':checked')
    • Use $.data(this, 'thing') instead of $(this).data('thing')
    • Any other case where creating a jQuery object isn't useful basically.
  3. Decending from an ID selector is preferred for performance...how specific do you need to be? That completely depends, in short: be as specific as you need to be.

笔芯 2024-09-16 06:49:49

1) 赋值与 jQuery 调用

引用 jQuery 的 $(this) 时是否应用相同的规则?

是的,绝对是。对 $ 函数的调用会创建一个新的 jQuery 对象,并随之产生相关的开销。使用同一选择器多次调用 $ 每次都会创建一个新对象。

2) this 与 $(this)

我想说知道差异很重要,因为有时不使用 jQuery 包装对象变得至关重要。在大多数情况下,您不想进行过早的优化,只是为了保持一致,始终用 $(this) 包装它们,并且最好将其缓存在变量中。但是,考虑一下包含一百万个

  • 元素的无序列表
      的极端示例:
  • $("#someList  li").each(function() {
        var id = $(this).attr('id');
    });
    

    将创建一百万个新对象,这将导致显着的损失。性能损失,而您根本可以在不创建任何新对象的情况下完成。对于在所有浏览器中一致的属性和属性,您可以直接访问它们,而无需将其包装在 jQuery 中。但是,如果这样做,请尝试将其限制在处理大量元素的情况下。

    3)特异性越高越好吗?

    并非总是如此。它主要取决于浏览器,并且再次不值得深入研究微优化,除非您确定应用程序中某些东西运行得相当慢。例如:

    $("#someElement") vs $("#someElement", "#elementsContainer")
    

    由于我们在通过 id 搜索元素时还提供了上下文,因此第二个查询可能会更快,但事实恰恰相反。第一个查询会转换为对本机 getElementById(..) 的直接调用,而第二个查询则不会,因为上下文选择器。

    此外,某些浏览器可能会提供一个接口来使用 getElementsByClassName 按类名访问元素,并且 jQuery 可能会在这些浏览器中使用它以获得更快的结果,在这种情况下提供更具体的选择器,例如:

    $("#someElement.theClass")
    

    实际上可能比简单地写成一个障碍:

    $(".theClass")
    

    1) Assignment vs jQuery Calls

    Does this same rule apply when referencing jQuery's $(this)?

    Yes, absolutely. A call to the $ function creates a new jQuery object and with it comes associated overhead. Multiple calls to $ with the same selector will create a new object every time.

    2) this vs $(this)

    I would say knowing the difference is important because at times it becomes crucial that you don't wrap your objects with jQuery. In most cases, you wouldn't want to do premature optimization and just to keep things consistent, always wrap them with $(this), and preferably cache it in a variable. However, consider this extreme example of an unordered list <ul> that contains a million <li> elements:

    $("#someList  li").each(function() {
        var id = $(this).attr('id');
    });
    

    A million new objects will be created which will incur a significant performance penalty, when you could have done without creating any new objects at all. For attributes and properties that are consistent across all browsers, you could access them directly without wrapping it in jQuery. However, if doing so, try to limit it to cases where lots of elements are being dealt with.

    3) Is more specificity always better?

    Not always. It mostly depends on browsers, and again not worth delving into micro-optimizations unless you know for sure that something is running rather slow in your application. For example:

    $("#someElement") vs $("#someElement", "#elementsContainer")
    

    It may appear that since we are also provide a context when searching an element by id, that the second query is going to be faster, but it's the opposite. The first query translates to a direct call to the native getElementById(..) while the second one doesn't because of the context selector.

    Also, some browsers might provide an interface to access elements by class name using getElementsByClassName and jQuery might be using it for those browsers for faster results, in which case providing a more specific selector such as:

    $("#someElement.theClass")
    

    might actually be a hindrance than simply writing:

    $(".theClass")
    
    错々过的事 2024-09-16 06:49:49

    该博客不太过时,但它为您的问题提供了一些答案,并提供了有关使用 jquery 时加快网站速度的更多信息: http://www.artzstudio.com/2009/04/jquery-performance-rules/

    我最喜欢的之一是第六条,它指出限制DOM 操作。在 for 循环中执行 .append 总是一件坏事,因为每次追加到 DOM 时,这是一项昂贵的操作。

    This blog isn't too dated, but it supplies some answers to your questions as well as gives some more info on speeding up your site when using jquery: http://www.artzstudio.com/2009/04/jquery-performance-rules/

    One of my favorites is number six which states to limit DOM manipulation. It's always a bad thing to do a .append in a for loop since each time you are appending to the DOM, which is an expensive operation.

    晌融 2024-09-16 06:49:49

    根据您的问题:

    1. 缓存 jQuery 对象应该会产生最佳性能。它将避免 DOM 查找,这种查找在执行多次时会变慢。您可以从 jQuery 链接中受益 - 有时不需要局部变量。
    2. this 是 DOM 元素时,$(this) 也是如此。尽管这是获取 jQuery 对象最快的方法,但它仍然比缓存慢。如果普通 DOM 元素就足够了 - 那么根本就不要调用 jQuery。带有 id 属性的示例非常出色 - 如果您不需要 $(this) ,则更喜欢 this.id 而不是 $(this).attr('id)
    3. 更具体的选择器确实会减少 DOM 查找时间。然而,确实有一条线需要划定——只有当您 100% 确定这会显着提高性能时,才使选择器更加具体。

    Up to your questions:

    1. Caching the jQuery object should yield best performance. It will avoid DOM lookups which is what can get slow when performed many times. You can benefit from jQuery chaining - sometimes there is no need for a local variable.
    2. The same goes with $(this) when this is a DOM element. Despite the fact that this is the fastest way to obtain a jQuery object it is still slower than caching. If the vanilla DOM element would suffice - then don't call jQuery at all. The example with the id attribute is excellent - prefer this.id than $(this).attr('id) if you are not going to need $(this)
    3. More specific selectors will decrease the DOM lookup time indeed. However there is indeed a line to be drawn - make the selectors more specific only if you are 100% sure this would improve performance in a noticeable way.
    暗地喜欢 2024-09-16 06:49:49

    您应该关注的唯一情况是循环事件。因为您在其中之一中所做的每个操作都将在每次迭代或每个事件中完成。

    1. 赋值与 jQuery 调用

      你的例子不是最好的。您应该保存对 jQuery 对象引用的位置是循环事件中使用的对象,或者是复杂查询的结果。

    2. 这个 vs $(this)

      同样,在性能关键情况下,原始 dom 更好。 其他除此之外,您应该选择更短或更可读。令人惊讶的是,令人惊讶的是,它并不总是 jQuery。

    3. 越具体就越好吗?

      还有更多类型的特异性,通常会被人们混淆。其中一个无用,例如:id选择器tag#id的标签名称,它会比简单的id慢。但还有另一种类型,具体而言,它会带来巨大的好处
      现在这种类型取决于浏览器,因为现代的浏览器会牺牲旧的浏览器,但这是值得的权衡当您为 class 指定 tag 时,就会发生这种情况标签.class。在 IE 6-7 中,它将比简单的 .class 快得多,因为 sizzle 可以利用快速的 document.getElementsByTagName 函数。现在另一种类型是当您指定太多祖先时。这会在每个浏览器中减慢速度。这是因为选择器是从右向左执行的。要记住的规则:始终尽可能具体地选择最右边的选择器

    The only situations you should keep your eye on are loops and events. Because every action you make in one of these will be done in every iteration or on every event.

    1. Assignment vs jQuery Calls

      Your example is not the best. The place where you should save references to jQuery objects are the ones used in loops or events, or which are results of complex queries.

    2. this vs $(this)

      Again in performance critical situations raw dom is better. Other than that you should chose which is shorter or more readable. Surprise, surprise it's not always jQuery.

    3. Is more specificity always better?

      There are more types of specificity which are usually confused by people. One of them is useless which e.g.: a tag name for an id selector tag#id, it will be slower than a simple id. But there is another type when it will be a huge benefit to be specific.
      Now this type depends on the browser, because the modern ones will sacrifice for the old ones, but it worths the trade-off This happens when you specify a tag for a class tag.class. In IE 6-7 it will be significantly faster than a simple .class, because sizzle can make use of the fast document.getElementsByTagName function. Now another type is when you specify too much ancestors. This will slow things down in every browser. This is because the selector is executed from right to left. The rule to keep in mind: always be the rightmost selector as specific as possible.

    故笙诉离歌 2024-09-16 06:49:49

    2013 年关于最佳 jQuery 实践的博客文章

    更新了您问题的答案,甚至更多关于当今应用的最佳 jQuery 实践的信息,这篇文章正在处理非常有帮助并且您可能想要的有趣主题阅读。

    它涉及这里提出的主题,甚至更多:动画函数、jQuery 承诺、导入 jQuery 的最佳方法、jQuery 事件等。
    希望对您有所帮助!

    2013 blog article about the best jQuery practices

    Updated answers on your question and even more regarding the best jQuery practices to apply nowadays, this article is dealing with interesting subjects that are really helpful and that you might want to read.

    It deals with the subjects asked here and even more: the animate function,jQuery promises, best ways to import jQuery, jQuery events etc.
    Hope that will be helpful to you!

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文