且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有哪些提高jQuery性能的快速技巧?

更新时间:2023-11-17 10:55:46

  1. 首先仅通过ID 优先选择简单选择,然后仅标签名称优先选择简单选择.通过类名或CSS选择器进行选择需要jQuery遍历DOM,而ID和标记则映射到本机"浏览器DOM函数(getElementById和getElementByTagName).
  2. 尽可能
  3. 缓存您的jQuery对象.
  4. 将您的操作
  5. 作用域限制在jQuery根对象上.与其单独选择元素,不如选择一个共同的祖先元素,并使用find函数在该元素子元素的范围内查找元素.实际上,只有在您对共同祖先执行某些操作的情况下,这才是***选择.否则,找到祖先并将其缓存的开销可能会超过范围遍历的好处.
  6. 不要使用$.each()请使用for(;;).快了十倍.
  1. Prefer simple selection first only by ID, and second only by tag name. Selecting by class name or CSS selector requires jQuery to walk the DOM, while ID and tag map to "native" browser DOM functions (getElementById and getElementByTagName).
  2. Cache your jQuery objects as much as possible.
  3. Scope your operations to a root jQuery object. Rather than selecting elements individually, select a common ancestor element and use the find function to find elements within the scope of that elements children. This is really only optimal if you are performing some operations on the common ancestor anyway; otherwise the overhead of finding the ancestor and caching it may outweigh the benefit of scoped traversal.
  4. Don't use $.each(), use for(;;) instead. It's over ten times faster.