如何获取当前执行的 javascript 代码的文件路径

2022-01-25 00:00:00 absolute-path include javascript src

我正在尝试执行 C #include "filename.c" 或 PHP include(dirname(__FILE__)."filename.php") 之类的操作但在javascript中.我知道如果我可以获取加载 js 文件的 URL(例如标签的 src 属性中给出的 URL),我可以做到这一点.javascript有什么办法知道吗?

I'm trying to do something like a C #include "filename.c", or PHP include(dirname(__FILE__)."filename.php") but in javascript. I know I can do this if I can get the URL a js file was loaded from (e.g. the URL given in the src attribute of the tag). Is there any way for the javascript to know that?

或者,有没有什么好方法可以从同一个域动态加载 javascript(不知道具体的域)?例如,假设我们有两个相同的服务器(QA 和生产),但它们显然具有不同的 URL 域.有没有办法像 include("myLib.js"); 这样 myLib.js 将从加载它的文件的域中加载?

Alternatively, is there any good way to load javascript dynamically from the same domain (without knowing the domain specifically)? For example, lets say we have two identical servers (QA and production) but they clearly have different URL domains. Is there a way to do something like include("myLib.js"); where myLib.js will load from the domain of the file loading it?

如果措辞有点混乱,请见谅.

Sorry if thats worded a little confusingly.

推荐答案

在脚本内:

var scripts = document.getElementsByTagName("script"),
    src = scripts[scripts.length-1].src;

这是因为浏览器按顺序加载和执行脚本,所以当你的脚本正在执行时,它所包含的文档肯定会将你的脚本元素作为页面上的最后一个元素.当然,这段代码对于脚本来说必须是全局的",所以将 src 保存在以后可以使用的地方.通过将全局变量包装起来避免泄漏:

This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

(function() { ... })();

相关文章