在jQuery 中動態加載 CSS 文件有多種方法,以下是幾種常用實現方式:
方法 1:創建 <link>
標簽(推薦)
// 動態加載外部 CSS 文件
function loadCSS(url) {$('<link>', {rel: 'stylesheet',type: 'text/css',href: url}).appendTo('head');
}// 使用示例
loadCSS('https://example.com/style.css');
方法 2:通過 AJAX 加載 CSS 內容
// 直接注入 CSS 代碼(適合小文件或動態樣式)
$.get('path/to/your.css', function(css) {$('<style type="text/css">\n' + css + '</style>').appendTo('head');
});
方法 3:使用回調檢測加載狀態
// 帶成功/失敗回調的 CSS 加載
function loadCSS(url, success, error) {const link = $('<link>', {rel: 'stylesheet',href: url}).appendTo('head');// 檢測加載狀態(注意:部分瀏覽器不支持 link.onload)link[0].onload = function() { success && success() };link[0].onerror = function() { error && error() };
}// 使用示例
loadCSS('theme.css', () => console.log('CSS 加載成功!'),() => console.error('CSS 加載失敗!')
);
方法 4:動態切換主題(結合 CSS 類)
// 存儲主題 URL
const themes = {dark: 'css/dark-theme.css',light: 'css/light-theme.css'
};// 切換主題函數
function switchTheme(themeName) {// 移除舊主題$('link[data-theme]').remove();// 添加新主題$('<link>', {rel: 'stylesheet','data-theme': themeName,href: themes[themeName]}).appendTo('head');
}// 使用示例
$('#btn-dark').click(() => switchTheme('dark'));
$('#btn-light').click(() => switchTheme('light'));
注意事項:
- 跨域問題:如果 CSS 文件在外部域名,確保服務器配置了正確的 CORS 策略
- 性能優化:避免重復加載相同 CSS(可通過檢查
<link>
是否存在) - 兼容性:
onload
事件在舊版 IE 中支持有限,可用setInterval
檢測sheet.cssRules
屬性作為降級方案 - 推薦方法:優先使用創建
<link>
標簽的方式(支持緩存且符合瀏覽器加載機制)
完整示例:帶重復加載檢查
function loadCSS(url, id) {// 檢查是否已存在if ($('link#' + id).length) return; $('<link>', {id: id,rel: 'stylesheet',href: url}).appendTo('head');
}// 使用
loadCSS('popup.css', 'popup-styles');
根據需求選擇合適的方法,通常方法 1 是最簡單且符合標準的方式。