如何获取javascript文件的位置(src)? [英] How to get the location (src) of a javascript file?
问题描述
javascript文件如何知道它位于何处?例如:
How can a javascript file know where it is located? For example:
<script type="text/javascript" src="http://mysite.com/scripts/howdy.js"></script>
中的代码怎么样howdy.js
了解 http://mysite.com/scripts/howdy.js
?
编辑:澄清。我不能依赖于在DOM中搜索我的脚本标记,因为我需要在DOM准备好之前了解它。
Clarification. I cannot rely on searching the DOM for my script tag because I need to know about it before the DOM may be ready.
推荐答案
在当前脚本执行的那一刻,它将是DOM中的最后一个脚本
元素,因此您可以通过以下方式获取它:
In the moment in which the current script is being executed, will be the last script
element in the DOM, therefore you can get it by:
var scripts = document.getElementsByTagName('script'),
currentScriptSrc = scripts[scripts.length-1].src;
检查这个脚本的noreferrer>示例。
Check this example that loads this script.
编辑:考虑@ kangax的评论,关于 async
和推迟
属性,IMO以前知道文件名的唯一安全方法是检查页面上的脚本
元素,检查它的 src
属性,一些库如 Scriptaculous。我们使用这种技术,例如:
Taking in consideration the @kangax's comment, about the async
and defer
attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script
elements on the page, examining its src
attribute, some libraries like Scriptaculous.us use this technique, for example:
var scripts = document.getElementsByTagName('script'),
len = scripts.length,
re = /howdy\.js$/,
src, howdyScriptSrc;
while (len--) {
src = scripts[len].src;
if (src && src.match(re)) {
howdyScriptSrc = src;
break;
}
}
这篇关于如何获取javascript文件的位置(src)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!