网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2025/5/18 浏览:3 次 )
背景
同事提了一个问题,如何在浏览器中动态插入的 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

上一篇:表单切换,用回车键替换Tab健(不支持IE)
下一篇:NodeJS框架Express的模板视图机制分析
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap