在瀏覽器中擷取當前執行的指令檔名的代碼

來源:互聯網
上載者:User

背景
同事提了一個問題,如何在瀏覽器中動態插入的 JavaScript 檔案中,擷取當前檔案名稱?

除了伺服器輸出一個檔案名稱外,在指令碼中擷取應該只有下面三種做法。

解法A
普遍的解法,只能用於頁面靜態scripts標籤引入或者單個動態載入。
複製代碼 代碼如下:
var scripts = document.getElementsByTagName('script');
var filename = scripts[scripts.length -1].src;

動態插入多個指令碼標籤的情況:
複製代碼 代碼如下:
loadScript('b.js?param=1')
loadScript('a.js?param=2')
loadScript('b.js?param=3')
loadScript('a.js?param=4')

/* 輸出
a.js >>> http://localhost:800/io/a.js?param=4
a.js >>> http://localhost:800/io/a.js?param=4
b.js >>> http://localhost:800/io/a.js?param=4
b.js >>> http://localhost:800/io/a.js?param=4
*/

解法B
變態型,只能工作於FireFox:
複製代碼 代碼如下:
try {
throw new Error();
}
catch(exception){
console.log( exception.fileName );
}

解法C
我的解法,操作原始碼:
複製代碼 代碼如下:
requireScript('a.js?'+Date.now(),function(text,src) {
console.log('text:',text);
globalEval('(function() { \nvar __filename = "'+ src +'";\n'+ text +'\n;})();');
})

瀏覽器輸出:
複製代碼 代碼如下:
<script>(function() {
var __filename = "a.js?1310971812334";
var scripts = document.getElementsByTagName('script');
console.log('a.js',' >>> ',scripts[scripts.length -1].src);
console.log(__filename);
;})();</script>

優點:可靠、可緩衝、可延遲執行、可擴充。
限制:1)變數命名被約定為“__filename”;2)同源策略。
又想到這個載入策略用來載入流行的 CoffeeScript,比如:
複製代碼 代碼如下:
requireScript('script.coffee',function(text,src) {
if( isCoffeeScript(src) )
globalEval( CoffeeScript.compile(text) );
})

連結

Cross-Origin Resource Sharing

Passing JavaScript arguments via the src attribute

CoffeeScript

查看或下載

https://gist.github.com/1088730

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.