jQuery 雖老但仍活躍於存量項目。遵循現代最佳實踐能顯著提升性能、可維護性與團隊協作效率。本文匯總 6 大維度 30+ 條核心準則,附代碼對比與原理解析。
<script src="//cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> —— 免費、全球加速、瀏覽器緩存命中率高<script>window.jQuery || document.write('<script src="/js/jquery-3.7.1.min.js"></script>')</script>
//cdn... 自動適配 HTTP/HTTPS,避免混合內容警告<script> 放在 </body> 前,不阻塞頁面渲染3.7.1),勿用 3.7 或 3 避免非預期更新$.noConflict(true) 釋放 $$ 時,全量使用 jQuery,調用 $.noConflict()$ 前綴:var $btn = $("#btn");var $list = $(".list"); 避免重複查找userList、apiUrl| ❌ 反模式 | ✅ 最佳實踐 | 原理 |
|---|---|---|
$("div.products") |
$(".products") |
類選擇器不指定標籤,減少標籤過濾 |
$("#outer #inner") |
$("#inner") |
ID 唯一,無需祖先限定 |
$("#parent .child") |
$("#parent").find(".child") |
ID 定位後 find 走原生 getElementById + 子樹查找,跳過 Sizzle |
$('.class') |
$('.class', '#container') |
指定 context 縮小查找範圍 |
$('div.container > *') |
$('div.container').children() |
避免通配符 *,用原生 children |
$('div.someclass :radio') |
$('div.someclass input:radio') |
顯式標籤避免隱式 * |
$('div.data table.attendees td.gonzalez') |
$('.data td.gonzalez') |
去除冗余中間層級 |
$('#id .class') |
$('#id').find('.class') |
同 #inner 優化 |
var $list = $("#list > ul").detach();
// 大量操作 $list...
$list.appendTo("#list");
// 差
for(i) $list.append("- " + i + "
");
// 好
var html = "";
for(i) html += "- " + i + "
";
$list.html(html);
// 最好:陣列 join(避免字符串不可變導致的中間副本)
var arr = [];
for(i) arr[i] = "- " + i + "
";
$list.html(arr.join(""));
var $el = $("#maybeExist");
if ($el.length) $el.slideUp(); // 避免空集合跑完動畫隊列
$(initPage),邏輯集中、易調試// 差
$("#btn").on("click", function() {...});
// 好
function handleBtnClick() {...}
$("#btn").on("click", handleBtnClick);
便於調試(堆棧顯示函數名)、解綁、單測、復用
$(document).ready(initPage) 或 $(initPage)<script src="app.js"></script> + $(initPage)<a onclick="..."> → $("#link").on("click", handler)$("#btn").on("click.myModule", handler);
$("#btn").off("click.myModule"); // 精準解綁,不影響其他模塊
$("#staticParent").on("click", ".dynamicChild", handler);
$.ajax(),.get()/.getJSON() 內部轉調用它url: "//api.example.com/data"data 對象,不拼接 URLdataType: "json"$("#parent").on("click", "a", handler)$.ajax({...}).done(success).fail(error);
// 或
var xhr = $.ajax({...});
xhr.done(success).fail(error);
var xhr = $.ajax({
url: url,
type: "GET",
cache: true,
data: { param1: "val1" },
dataType: "json",
jsonp: "callback",
statusCode: { 404: h404, 500: h500 }
});
xhr.done(onSuccess).fail(onError);
$.fx.speeds._default = 300、easing: "swing".show()/.hide()/.toggle(),複雜動畫用 .animate()prefers-reduced-motion:@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
// app.js
var App = (function($) {
var config = { apiBase: "/api" };
var modules = {};
function init() {
modules.header = new HeaderModule();
modules.list = new ListModule();
bindGlobalEvents();
}
function bindGlobalEvents() {
$(document).on("click.app", "[data-action]", function() {
var action = $(this).data("action");
var module = modules[action.split(".")[0]];
if (module && module[action.split(".")[1]]) {
module[action.split(".")[1]]($(this));
}
});
}
return { init: init, config: config, modules: modules };
})(jQuery);
$(App.init); // DOMReady 入口
jQuery 最佳實踐的核心是「約定優於配置、顯式優於隱式、緩存優於重複、委託優於直接、Promise 優於回調」。將這 30+ 條準則內化為團隊編碼規範,配合 ESLint 規則(jquery/no-ajax-cache、jquery/no-deprecated 等)自動檢查,可讓老項目煥發新生,也為未來遷移至 Vue/React 打下紮實基礎。