2011-04-17 41 views
2

如果我加載JavaScript源文件,像這樣:檢索JavaScript源文件位置?

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="src/file.js"></source> 
    </head> 
    <body> 
    </body> 
</html> 

我的問題是,如何才能file.js知道它的位置的相對路徑是src/?我需要這些信息來構建源文件中的URL,這取決於它從中加載的URL。

回答

2
<script src="src/file.js" id="script0"></script> 

在file.js:

var path = document.getElementById ("script0").getAttribute ("src"); 
+0

我自己也想過:)。我將獲取所有腳本元素,循環遍歷它們,並使用簡單的正則表達式替換來獲取相對路徑(如果匹配的是src)。 – Tower 2011-04-17 11:18:15