前端動態載入資源(腳本、樣式、圖片)時,需將相對路徑(./img.png、../api/user)解析為絕對 URL,避免基準路徑變更導致 404。
function canonical_uri(src, base_path) {
var root_page = /^[^?#]*\//.exec(location.href)[0],
root_domain = /^\w+:\/\/[^\/]+/.exec(root_page)[0],
absolute_regex = /^\w+:\/\//;
// 1. 協議相對 // → 補上 location.protocol
if (/^\/\//.test(src)) src = location.protocol + src;
// 2. 相對路徑(非 / 開頭、非絕對協議) → 加上 base_path
else if (!absolute_regex.test(src) && src.charAt(0) !== '/')
src = (base_path || '') + src;
// 3. 確保回傳絕對路徑
return absolute_regex.test(src) ? src :
(src.charAt(0) === '/' ? root_domain : root_page) + src;
}
測試:當前頁 https://example.com/hzt/index.html → canonical_uri("scy.js") 回傳 https://example.com/hzt/scy.js。
function getAbsoluteUrl(url) {
var img = new Image();
img.src = url; // 觸發網路請求(即使 abort 仍有成本)
url = img.src; // 瀏覽器自動解析為絕對 URL
img.src = null; // 取消請求
return url;
}
缺點:
① 產生真實 HTTP 請求(DevTools 顯示 Aborted)。
② IE6 不支援 new Image() 解析相對路徑。
③ 效能差、有副作用。
function getAbsoluteUrl(url) {
var a = document.createElement('a');
a.href = url; // 瀏覽器自動解析
return a.href; // 取得絕對 URL
}
優點:無網路請求、程式碼極簡。
缺點:IE6/7 不支援 a.href 自動解析;需插入 DOM 才觸發解析(會觸發重繪)。
function toAbsolute(url, base = location.href) {
return new URL(url, base).href;
}
core-js 或 url-polyfill)。| 方案 | IE6/7 | IE8+ | 現代瀏覽器 | 網路請求 | 效能 | 推薦度 |
|---|---|---|---|---|---|---|
| LABjs 字串解析 | ✅ | ✅ | ✅ | 無 | 高 | ★★★★☆ |
| Image 物件 | ❌ | ✅ | ✅ | 有 | 低 | ★☆☆☆☆ |
| Anchor 元素 | ❌ | ✅ | ✅ | 無 | 高 | ★★★☆☆ |
| URL API + Polyfill | ✅* | ✅ | ✅ | 無 | 高 | ★★★★★ |
// jQuery
console.log($anchor[0].href); // 絕對路徑(瀏覽器解析後)
console.log($anchor.attr('href')); // 原始相對路徑(HTML 屬性值)
new URL(),搭配 core-js/stable Polyfill。canonical_uri 函式,零依賴、零請求、全相容。new Image() 方案,除非極特殊情境需觸發預載。選對工具,相對路徑轉換不再是前端開發的痛點。