如何获取当前正在执行的 javascript 代码的文件路径
我正在尝试执行类似于 C #include "filename.c"
或 PHP include(dirname(__FILE__)."filename.php")
的操作,但在 javascript 中。我知道如果我可以获得加载 js 文件的 URL(例如标签的 src 属性中给出的 URL),我就可以做到这一点。有什么办法让 javascript 知道这一点吗?
或者,有没有什么好方法可以从同一域动态加载javascript(无需具体了解域)?例如,假设我们有两个相同的服务器(QA 和生产),但它们显然具有不同的 URL 域。有没有办法做类似 include("myLib.js");
的事情,其中 myLib.js 将从加载它的文件的域加载?
抱歉,如果措辞有点令人困惑。
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
在脚本内:
这是有效的,因为浏览器按顺序加载并执行脚本,因此在执行脚本时,包含该脚本的文档肯定会将您的脚本元素作为页面上的最后一个元素。当然,此代码对于脚本来说必须是“全局”的,因此请将
src
保存在以后可以使用的地方。通过将全局变量包装在以下内容中来避免泄漏:Within the script:
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:除 Internet Explorer(任何版本)之外的所有浏览器都有
文档。 currentScript
,它始终有效(无论文件是如何包含的(异步、小书签等))。如果您想知道您现在所在的 JS 文件的完整 URL:
Tadaa。
All browsers except Internet Explorer (any version) have
document.currentScript
, which always works always (no matter how the file was included (async, bookmarklet etc)).If you want to know the full URL of the JS file you're in right now:
Tadaa.
我刚刚做了这个小把戏:
✅ 适用于:Chrome、Firefox、Edge、Opera
尽情享受!
I just made this little trick :
✅ Works on: Chrome, Firefox, Edge, Opera
Enjoy !
如果您的文档中有内联脚本,则此处接受的答案不起作用。为了避免这种情况,您可以使用以下命令仅定位具有
[src]
属性的标记。
这有效地捕获了最后一个外部 .js 文件,解决了我使用内联 JS 模板遇到的一些问题。
The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target
<script>
tags with a[src]
attribute.This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.
根据此处找到的答案,我得出以下结论:
getCurrentScript.js
getCurrentScriptPath.js
顺便说一句:我正在使用 CommonJS
模块格式并与 webpack 捆绑。
Refining upon the answers found here I came up with the following:
getCurrentScript.js
getCurrentScriptPath.js
BTW: I'm using CommonJS
module format and bundling with webpack.
我最近发现了一种更简洁的方法,它可以随时执行,而不是在脚本加载时被迫同步执行。
使用 stackinfo 获取当前位置的堆栈跟踪,并获取
info.file
名称位于堆栈顶部。I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.
Use stackinfo to get a stacktrace at a current location, and grab the
info.file
name off the top of the stack.我编写了一个简单的函数,它允许使用 try/catch 方法获取当前 javascript 文件的绝对位置。
您可以在此处查看它。
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
You can see it here.
完善此处找到的答案:
小技巧
getCurrentScript 和 getCurrentScriptPath
我想出了以下内容:
Refining upon the answers found here:
little trick
getCurrentScript and getCurrentScriptPath
I came up with the following:
无论它是脚本、html 文件(例如框架)、css 文件、图像还是其他任何文件,如果您不指定服务器/域,则 html 文档的路径将是默认,因此您可以执行以下操作,例如
或
如果您不提供服务器/域,则路径将相对于任一路径主文档路径的页面或脚本
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
我可能误解了您的问题,但只要生产和开发服务器使用相同的路径结构,您似乎就应该能够使用相对路径。
I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.
我整理了一些意大利面条代码,这些代码将使当前的 .js 文件运行(例如,如果您使用“node”运行脚本。您可以使用它来获取正在运行的脚本的目录)
这将其获取为“file” ://path/to/directoryWhere/fileExists"
这需要一个 npm 包(我确信它也在其他平台上):
npm i stackinfo
import stackinfo from 'stackinfo';
或var {stackinfo} = require("stackinfo");
I've thrown together some spaghetti code that will get the current .js file ran (ex. if you run a script with "node ." you can use this to get the directory of the script that's running)
this gets it as "file://path/to/directoryWhere/fileExists"
this requires an npm package (im sure its on other platforms as well):
npm i stackinfo
import stackinfo from 'stackinfo';
orvar {stackinfo} = require("stackinfo");
在 ES6 模块环境中,当前正在执行的模块的 URL 可以从 'import.meta' 属性获取。请参阅 MDN 文档。
另请参阅 document.currentScript is null (Don Park 的回答)
一个示例:
下面是 在模块环境中使用,该模块正在 HTML 脚本元素中加载
控制台输出如下:
In an ES6 module environment, the URL of the currently executing module can be obtained from 'import.meta' property. Refer MDN Document.
Also refer document.currentScript is null (Don Park's answer)
Below is an example:
The above is being used in a module environment, where the module is being loaded in HTML script element
The console output is as follows: