演進歷程對比
| 時代 | 方案 | 特點 | 缺陷 |
| 遠古 | document.write | 同步阻塞 | 阻塞渲染,異步失效,XSS 風險 |
| 古典 | 創建 script 標籤 + onload | 異步非阻塞 | 無模塊系統,依賴管理困難 |
| 模塊化萌芽 | RequireJS / SeaJS (AMD/CMD) | 依賴聲明、按需加載 | 配置繁瑣,非標準 |
| 現代標準 | ES Module (import/export) | 靜態分析、Tree-shaking、瀏覽器原生 | 舊瀏覽器需打包編譯 |
| 動態導入 | import() / System.import() | 運行時按需加載、代碼分割 | 需打包工具支持 |
原生 script 標籤動態加載(通用基礎方案)
/**
* 動態加載腳本(Promise 版)
* @param {string} src - 腳本 URL
* @param {Object} attrs - 額外屬性 {id, async, defer, crossorigin, integrity}
* @returns {Promise}
*/
function loadScript(src, attrs = {}) {
return new Promise((resolve, reject) => {
// 去重:已加載同 src 腳本直接 resolve
var existing = document.querySelector('script[src="' + src + '"]');
if (existing) return resolve(existing);
var script = document.createElement('script');
script.src = src;
script.async = attrs.async !== false; // 默認 async
// 設置額外屬性
Object.keys(attrs).forEach(key => {
if (key !== 'async') script.setAttribute(key, attrs[key]);
});
script.onload = () => resolve(script);
script.onerror = () => reject(new Error('腳本加載失敗: ' + src));
document.head.appendChild(script);
});
}
// 使用
loadScript('https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js', {
integrity: 'sha256-xxx',
crossorigin: 'anonymous'
}).then(() => {
console.log(_.VERSION); // lodash 可用
}).catch(err => {
console.error(err);
});
批量加載與依賴管理
/**
* 按序加載多個腳本(有依賴關係時)
* @param {string[]} urls
* @returns {Promise}
*/
function loadScriptsSequential(urls) {
return urls.reduce((promise, url) =>
promise.then(() => loadScript(url)),
Promise.resolve()
);
}
/**
* 並行加載無依賴腳本
* @param {string[]} urls
* @returns {Promise}
*/
function loadScriptsParallel(urls) {
return Promise.all(urls.map(loadScript));
}
// 使用:先加載 jQuery,再加載依賴 jQuery 的插件
loadScriptsSequential([
'https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js',
'https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js'
]).then(() => {
$('#form').validate({ /* ... */ });
});
ES Module 動態導入(現代標準)
// 瀏覽器原生支持(需