背景 同事提了一个问题,如何在浏览器中动态插入的 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
推荐阅读
基于jquery实现的鼠标滑过按钮改变背景图片
复制代码 代码如下: $(document).ready(function () { //按钮样式切换 $("#btFeedBack").hover( function () { $(this).removeClass("btFeed").addClass("btFeedhover"); }, function () { $(this).removeClass("b>>>详细阅读
本文标题:在浏览器中获取当前执行的脚本文件名的代码
地址:http://www.17bianji.com/kaifa2/JS/24399.html
1/2 1