萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 選擇器快取最佳實踐:從全域變數到命名空間物件模式

重複呼叫 $('#id') 會導致瀏覽器反覆遍歷 DOM 樹,影響效能。本文示範如何將選擇器快取至模組物件,結合事件代理、模組化模式,實現高效能、可維護的 jQuery 代碼組織。

問題代碼:重複查詢 DOM

$(document).ready(function() {
  $('#some-selector').on('hover', function() {
    $(this).fadeOut('slow').delay(400).fadeIn();
    console.log($(this).text());
  });
  $('#another-element').on('hover', function() {
    $(this).slideUp();
  });
  $('#some-selector').on('click', function() { // 再次查詢 #some-selector
    alert('You have clicked a featured element');
  });
  $('#another-element').on('mouseout', function() { // 再次查詢
    $(this).slideUp();
  });
});

進階快取模式:命名空間物件

// 1. 定義選擇器映射表(集中維護、易重構)
const Selectors = {
  featured: '#some-selector',
  panel: '#another-element',
  modal: '.modal-overlay',
  // 複雜選擇器可用函數動態生成
  getRow: (id) => `#dataTable tr[data-id="${id}"]`
};

// 2. 快取 jQuery 物件(DOM Ready 後一次性查詢)
let $cache = {};

function initCache() {
  $cache = {
    $featured: $(Selectors.featured),
    $panel: $(Selectors.panel),
    $modal: $(Selectors.modal)
  };
}

// 3. 使用快取物件
$(document).ready(function() {
  initCache();

  $cache.$featured.on('hover', function() {
    $(this).fadeOut('slow').delay(400).fadeIn();
    console.log($(this).text());
  });

  $cache.$panel.on('hover', function() {
    $(this).slideUp();
  });

  $cache.$featured.on('click', function() {
    alert('You have clicked a featured element');
  });

  $cache.$panel.on('mouseout', function() {
    $(this).slideUp();
  });
});

進一步封裝:UI 元件模組模式

const FeaturedComponent = (function() {
  let $el, $panel;

  function cacheElements() {
    $el = $('#some-selector');
    $panel = $('#another-element');
  }

  function bindEvents() {
    $el.on('hover', onHover).on('click', onClick);
    $panel.on('hover mouseout', onPanelHover);
  }

  function onHover() {
    $(this).fadeOut('slow').delay(400).fadeIn();
    console.log($(this).text());
  }

  function onClick() {
    alert('Featured clicked');
  }

  function onPanelHover(e) {
    $(this)[e.type === 'mouseout' ? 'slideUp' : 'slideDown']();
  }

  return {
    init: function() {
      cacheElements();
      bindEvents();
    },
    refresh: function() { // 針對動態新增元素重新快取
      cacheElements();
      bindEvents();
    }
  };
})();

$(document).ready(() => FeaturedComponent.init());

動態內容場景:事件代理避免重複快取

// 容器不變,子元素動態新增/移除
$('#container').on('click', '.dynamic-item', function() {
  // this 為觸發事件的 .dynamic-item
  console.log($(this).data('id'));
});

// 無需重新快取 .dynamic-item,效能最優

效能對比(1000 次操作)

| 方式 | 耗時 | 備註 | |------|------|------| | 每次 $('#id') | ~15ms | 反覆遍歷 DOM | | 變數快取 const $el = $('#id') | ~0.2ms | 單次查詢,直接引用 | | 事件代理 | ~0.1ms | 無需快取子元素,容器固定 |

避坑指南

  • 快取失效:AJAX 替換容器 HTML 後,舊快取指向已移除的節點,需重新 initCache()。
  • 記憶體洩漏:快取大量已移除元素的 jQuery 物件,阻礙 GC。及時清空 $cache = {} 或用 WeakMap。
  • 選擇器變更:集中在 Selectors 物件修改,全局生效。
  • 不要快取集合後再過濾:$cache.$list.filter('.active') 仍會遍歷,不如重新查詢 $('.active', $container)。

選擇器快取是 jQuery 專案效能優化的第一步,配合模組化封裝與事件代理,能構建清晰、高效、可維護的前端代碼庫。

copyright © 萬盛學電腦網 all rights reserved