多庫共存時 (jQuery + Prototype + MooTools 等) 均佔用 $ 變量,後載入者覆蓋先載入者。
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
$('#msg').hide(); // jQuery 的 $
// Prototype 的 $ 不可直接訪問
</script>
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
$('#msg').hide(); // Prototype 的 $,報錯!
jQuery('#msg').hide(); // 必須用完整名稱
</script>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
// 釋放 $,歸還給 Prototype
const $j = jQuery.noConflict();
// 此後只能用 $j 或 jQuery
$j('#msg').hide();
jQuery('#msg').hide();
// $ 現在是 Prototype 的
$('msg').hide(); // Prototype 寫法
</script>
const $j = jQuery.noConflict();
$j('#msg').hide(); // 簡短別名
// 或
const jq = jQuery.noConflict();
jq('#msg').hide();
// 插件代碼
(function($) {
// 此處 $ 確定為 jQuery
$.fn.myPlugin = function(options) {
return this.each(function() {
$(this).css('color', 'red');
});
};
})(jQuery);
// 業務代碼同理
(function($) {
$(function() {
$('#msg').hide(); // 安全使用 $
});
})(jQuery);
// 或 DOMReady 簡寫
jQuery(function($) {
$('#msg').hide(); // 安全
});
(function($) {
// 1. 創建獨立作用域,避免污染全局
// 2. 參數 $ 接收傳入的 jQuery
// 3. 立即執行,返回值可導出
// 插件內部邏輯...
// 可選:返回公開 API
return { version: '1.0' };
})(jQuery); // 傳入真正的 jQuery
優勢:無視載入順序、無全局污染、參數名可任意 ($、jQ、$j)、支持多版本 jQuery 共存。
;(function($, window, document, undefined) {
'use strict';
const pluginName = 'myPlugin';
const defaults = { color: 'red' };
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
Plugin.prototype.init = function() {
$(this.element).css('color', this.options.color);
};
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, pluginName)) {
$.data(this, pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
// 不再需要 noConflict,直接 import
import $ from 'jquery';
import 'plugin-a';
import 'plugin-b';
$('#msg').hide(); // $ 確定為 jQuery
// 若需全局暴露 (如 legacy 代碼)
window.$ = window.jQuery = $;
noConflict() + 別名管理
4. 業務代碼優先用 jQuery 全稱或 IIFE 簡寫 jQuery($ => { ... })
5. 逐步遷移至原生 JS / 現代框架,減少 jQuery 依賴