在處理資源載入、路徑正規化、CSP 策略生成等場景時,常需將相對路徑 (如 ./assets/img.png、../api/user) 轉為絕對路徑。本文對比兩大類方案:瀏覽器原生 DOM 解析法與純 JavaScript 字串運算法,分析優缺點、相容性與效能。
function toAbsoluteUrl(href, base = document.baseURI) {
const a = document.createElement('a');
a.href = href; // 瀏覽器自動解析為絕對 URL
return a.href;
}
// 測試
toAbsoluteUrl('showroom/list'); // https://example.com/current/showroom/list
toAbsoluteUrl('../api/user'); // https://example.com/api/user
toAbsoluteUrl('/absolute/path'); // https://example.com/absolute/path
toAbsoluteUrl('https://other.com/path'); // https://other.com/path (不變)
✅ 優點:零依賴、標準合規、自動處理 ./、../、//、查詢字串、雜湊
✅ 可取得 a.protocol、a.host、a.pathname、a.search、a.hash 等解析屬性
⚠️ 注意:IE6-7 不支援,但現代專案已可忽略
<base href="https://example.com/app/">
// 之後所有相對路徑自動相對於此 base
// document.baseURI 會反映此值
function toAbsoluteUrlModern(href, base = document.baseURI) {
return new URL(href, base).href;
}
// 解析能力更強
const url = new URL('./path?query=1#hash', 'https://example.com/base/');
console.log(url.pathname); // /base/path
console.log(url.searchParams.get('query')); // 1
// 解析 URI 為元件
function parseURI(url) {
const m = String(url).trim().match(
/^([^:/?#]+:)?(\/\/([^:@]*?(?::[^:@]*)?@)?([^:/?#]*)(?::(\d*))?)?([^?#]*)(\?[^#]*)?(#.*)?/
);
return m ? {
href: m[0], protocol: m[1], authority: m[2], host: m[3],
hostname: m[4], port: m[5], pathname: m[6], search: m[7], hash: m[8]
} : null;
}
// 移除 . 與 .. 區段 (RFC 3986 5.2.4)
function removeDotSegments(input) {
const output = [];
input.replace(/^(\.?\/)+/, '') // 移除開頭 ./ 或 .
.replace(/\/(\.?\/)+/g, '/') // 移除中間 /./ 或 /.
.replace(/\/\.\.$/, '/..') // 結尾 /.. 保留
.replace(/\/[^/]*\/\.\.\//g, '/') // 移除 /xxx/../
.split('/').forEach(seg => {
if (seg === '..') output.pop();
else if (seg !== '.') output.push(seg);
});
return output.join('/');
}
// 合併基底與相對路徑
function absolutizeURI(base, href) {
const hrefObj = parseURI(href);
const baseObj = parseURI(base);
if (!hrefObj || !baseObj) return null;
const protocol = hrefObj.protocol || baseObj.protocol;
const authority = hrefObj.authority || baseObj.authority;
let pathname;
if (hrefObj.protocol || hrefObj.authority || hrefObj.pathname.startsWith('/')) {
pathname = removeDotSegments(hrefObj.pathname);
} else {
const basePath = baseObj.pathname.substring(0, baseObj.pathname.lastIndexOf('/') + 1);
pathname = removeDotSegments(basePath + hrefObj.pathname);
}
const search = hrefObj.search || baseObj.search;
const hash = hrefObj.hash;
return `${protocol}${authority}${pathname}${search}${hash}`;
}
| 維度 | <a> / new URL() | 純運算法 |
|---|---|---|
| 程式碼量 | 極少 (1-3 行) | 約 50-100 行 |
| 標準合規 | 瀏覽器原生保證 | 需自行測試邊界案例 |
| 環境需求 | 需 DOM / URL API | 純 JS,可用於 Worker、Node 早期版本 |
| 效能 | 極快 (原生 C++) | 較慢 (JS 字串操作) |
| IE 支援 | IE10+ (URL) / IE6+ (<a>) | 全版本 |
| 取得原始相對路徑 | a.getAttribute('href') | 原始輸入即為相對路徑 |
const $a = $('');
// 絕對路徑 (瀏覽器解析後)
console.log($a[0].href); // "https://example.com/current/relative/path"
console.log($a.prop('href')); // 同上
// 原始相對路徑 (HTML 屬性值)
console.log($a.attr('href')); // "./relative/path"
new URL(relative, base)document.createElement('a')const URL = require('url').URL 或 new URL() (實驗性)whatwg-url polyfill 或用成熟庫 url-join、resolve-urlpath-browserify (Node path API 移植) 或 upathbase + '/' + relative 會在雙斜線、..、查詢參數上翻車document.baseURI 可能受 `#fragment 不會發送給伺服器,純前端路由需自行解析路徑解析看似瑣碎,實則關係資源載入安全、CSP 策略正確性、單頁應用路由穩定。善用平台原生能力,少造輪子,更少 Bug。