哪个表现更好,检查课程或添加课程 [英] Which is performancewise better, check for class or add class

查看:58
本文介绍了哪个表现更好,检查课程或添加课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个触发滚动事件的功能,那就更好了。

If you have a function which fires on a scroll event, which is better.


  1. 检查是否已经添加了一个类,如果不添加它

  2. 不要做任何检查,只需在每次需要时添加课程。





$(document).on('scroll', function () {
   var scrollTop = $(this).scrollTop();
   if (scrollTop > 50) {
      if (!$("nav .branding").hasClass("collapse"))
         $("nav .branding").addClass("collapse");
   } else {
      if ($("nav .branding").hasClass("collapse"))
         $("nav .branding").removeClass("collapse");
   }
});

$(document).on('scroll', function () {
   var scrollTop = $(this).scrollTop();
   if (scrollTop > 50) {
      $("nav .branding").addClass("collapse");
   } else {
      $("nav .branding").removeClass("collapse");
   }
});

第一次有额外检查但在另一项行动中可能(?)是更多激烈的操作(?)

The first occasion there is an extra check but in the other action there might (?) be a more intense operation(?)

推荐答案

如果你担心表现,你可以/应该做些事:

If you are concerned about performance there are a few things you can/should do:

1。缓存你的选择器:

Dom交互很昂贵,在你的情况下你打电话给 $(nav .branding)多次。

Dom interaction is expensive, and in your case you call $("nav .branding") multiple times.

将其存储在一个变量中,如此 var $ branding = $(nav .branding)

Store it in a variable like so var $branding = $("nav .branding").

2。使用vanilla javascript来处理类

取决于浏览器支持

var branding = document.querySelector('nav .branding');

if (scrollTop > 50) {
  if (!branding.classList.contains("collapse")) {
    branding.classList.add("collapse");
  }
} else {
  if (branding.classList.contains("collapse")) {
    branding.classList.remove("collapse");
  }
}

请记住并非所有浏览器都支持 classList 属性,在你可以找到的MDN上有关兼容性和polyfill的信息

Please keep in mind that not all browsers support the classList property, on the MDN you can find information about compatibility and also a polyfill.

关于你的原始问题:jQuery的 addClass 有一个内置的检查是否已经存在该类,所以当你不事先使用 hasClass 时你最好去,因为它会导致冗余,但是要保留请注意 addClass ~70%性能低于 classList

Concerning your original question: jQuery's addClass has an inbuilt check whether the class already exists, so you're better to go when you dont use hasClass beforehand as it will cause redundancy, but do keep in mind that addClass is ~70% less performant than classList.

这篇关于哪个表现更好,检查课程或添加课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆