您的位置:首页 > 编程语言

在浏览器中获取当前执行的脚本文件名的代码

2011-07-19 00:00 429 查看
背景
同事提了一个问题,如何在浏览器中动态插入的 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: