萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 相對路徑轉絕對路徑:DOM 法 vs 純運算法完整對比

在處理資源載入、路徑正規化、CSP 策略生成等場景時,常需將相對路徑 (如 ./assets/img.png、../api/user) 轉為絕對路徑。本文對比兩大類方案:瀏覽器原生 DOM 解析法與純 JavaScript 字串運算法,分析優缺點、相容性與效能。

方案一:瀏覽器原生解析法(推薦現代環境)

1.1 `` 錨點元素法(最簡潔、標準)

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 不支援,但現代專案已可忽略

1.2 `` 標籤配合

<base href="https://example.com/app/">
// 之後所有相對路徑自動相對於此 base
// document.baseURI 會反映此值

1.3 `new URL()` 建構子 (現代標準,Node.js 10+ / 瀏覽器全支援)

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

方案二:純字串運算法(無 DOM 環境、極舊瀏覽器)

2.1 手寫 RFC 3986 解析器 (節錄核心邏輯)

// 解析 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')原始輸入即為相對路徑

jQuery 環境下的取值差異

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"

實戰建議

  1. 現代瀏覽器/Node 18+:直接用 new URL(relative, base)
  2. 需支援 IE11:用 document.createElement('a')
  3. Node.js 10-17:const URL = require('url').URL 或 new URL() (實驗性)
  4. 無 DOM 環境 (Worker/舊 Node):引入 whatwg-url polyfill 或用成熟庫 url-join、resolve-url
  5. 複雜路徑操作:使用 path-browserify (Node path API 移植) 或 upath

避坑清單

  • 不要手工字串拼接:base + '/' + relative 會在雙斜線、..、查詢參數上翻車
  • 注意 document.baseURI 可能受 `` 標籤影響
  • 雜湊 #fragment 不會發送給伺服器,純前端路由需自行解析
  • 跨域資源載入時,瀏覽器會阻擋,非路徑解析問題

路徑解析看似瑣碎,實則關係資源載入安全、CSP 策略正確性、單頁應用路由穩定。善用平台原生能力,少造輪子,更少 Bug。

copyright © 萬盛學電腦網 all rights reserved