在前端開發中,常有需要動態取得網站根目錄的需求,例如拼接靜態資源路徑或 API 位址。以下是一個簡短而實用的寫法。
<script>
function getRootPath() {
var strFullPath = window.document.location.href;
var strPath = window.document.location.pathname;
var pos = strFullPath.indexOf(strPath);
var prePath = strFullPath.substring(0, pos);
var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
return prePath + postPath;
}
var webpath = getRootPath(); // webpath 即為根目錄路徑
</script>
做法是先取出完整的網址與路徑部分,用 indexOf 找出路徑在完整網址中的起始位置,切出前面的「通訊協定+網域」片段;再從路徑中取出第一層目錄名稱,兩段拼接起來就是應用程式的根路徑。
在頁面可能被部署到虛擬目錄的情況下,寫死絕對路徑容易出錯,用這種動態計算的方式會更有彈性。不過若只是單純引用同目錄資源,直接用相對路徑通常就足夠了。