<base> 標籤用來給頁面中所有相對路徑指定一個基準地址,在做 CDN 分發、靜態化鏡像時經常用到。有時候我們需要在前端讀出這個基準地址,做法很簡單:給 base 標籤加上 id,然後讀它的 href 屬性。
<!DOCTYPE html>
<html>
<head>
<base id="htmldom" href="https://www.jb51.net/">
</head>
<body>
<p>Base URL is:
<script>
document.write(document.getElementById("htmldom").href);
</script>
</p>
</body>
</html>
運行結果:
Base URL is: https://www.jb51.net/
不給 base 加 id 也能取。頁面中 base 標籤最多隻有一個,可以直接用標籤選擇器:
var baseUrl = document.querySelector('base');
console.log(baseUrl ? baseUrl.href : document.location.origin);
需要注意的是,若頁面沒有 base 標籤,上面的寫法要加判空,否則會報錯。
base 會影響所有相對路徑。這是把雙刃劍:的好處是資源路徑集中管理,弊端是頁內錨點(<a href="#top">)和表單提交行為都會被基準地址帶走,容易出現意料之外的跳轉。使用 base 標籤時,錨點建議改寫成完整的 href="当前页面.html#top" 形式。
讀取當前真實地址用 location。如果目的是拿到頁面自身的 URL 而非基準地址,應該用 document.location.href,兩者含義完全不同,不要混用。