如何获取javascript文件的位置(src)? [英] How to get the location (src) of a javascript file?

查看:690
本文介绍了如何获取javascript文件的位置(src)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆