如何获取当前正在执行的 javascript 代码的文件路径
-
20-09-2019 - |
题
我正在尝试做类似 C 的事情 #include "filename.c"
, 或 PHP include(dirname(__FILE__)."filename.php")
但在 JavaScript 中。我知道如果我可以获得 js 文件加载的 URL(例如标签的 src 属性中给出的 URL)。有什么办法让 javascript 知道这一点吗?
或者,有没有什么好方法可以从同一域动态加载javascript(无需具体了解域)?例如,假设我们有两个相同的服务器(QA 和生产),但它们显然具有不同的 URL 域。有没有办法做类似的事情 include("myLib.js");
myLib.js 将从加载它的文件的域中加载?
抱歉,如果这措辞有点令人困惑。
解决方案
在该脚本中:
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
这工作,因为浏览器加载以及为了执行脚本,所以当你的脚本执行时,它被包含在文档肯定有你的脚本元素作为页面上的最后一个。当然,这代码必须是“全球性”的剧本,所以保存src
的地方在那里,你可以在以后使用它。避免在包装它泄漏全局变量:
(function() { ... })();
其他提示
除了IE(任何版本)了 document.currentScript
<所有浏览器/ A>,它始终工作总是(不管该文件是如何包括(异步,书签等))。
如果你想知道你现在是JS文件的完整网址:
var script = document.currentScript;
var fullUrl = script.src;
Tadaa。
如果你有你的文档中内嵌脚本这里接受的答案是行不通的。为了避免这种情况,你可以使用下面只定位<script>
标签与[src]
属性。
/**
* Current Script Path
*
* Get the dir path to the currently executing script file
* which is always the last one in the scripts array with
* an [src] attr
*/
var currentScriptPath = function () {
var scripts = document.querySelectorAll( 'script[src]' );
var currentScript = scripts[ scripts.length - 1 ].src;
var currentScriptChunks = currentScript.split( '/' );
var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];
return currentScript.replace( currentScriptFile, '' );
}
这有效地抓住了最后一个外部.js文件,解决一些问题,我与JS在线模板遇到。
我只是做这个小动作:
window.getRunningScript = () => {
return () => {
let err = new Error()
let link = err.stack.split('(')
link = link[1]
link = link.split(')')[0]
link = link.split(':')
link.splice(-2, 2)
link = link.join(':')
return link
}
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())
上工作:浏览器,Firefox,边缘
享受!
根据此处找到的答案,我得出以下结论:
getCurrentScript.js
var getCurrentScript = function () {
if (document.currentScript) {
return document.currentScript.src;
} else {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length-1].src;
}
};
module.exports = getCurrentScript;
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
我最近发现这种更清洁的方法,它可以在任何时间执行,而不是被迫同步做时,脚本加载。
使用 stackinfo 在当前位置获得一个堆栈跟踪,并抓住info.file
名字从顶部堆栈。
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
我已经通过使用一个try / catch方法编码的简单的功能,其允许获得当前JavaScript文件的绝对位置。
您可以看到它这里。
我可能会误解你的问题,但似乎你就应该能够只要生产和开发服务器使用相同的路径结构,使用相对路径。
<script language="javascript" src="js/myLib.js" />
不管它的一个脚本,一个HTML文件(用于帧,例如),CSS文件,图像,不管,如果不要指定服务器/域的HTML文档的路径将是默认的,所以你可以做,例如:
<script type=text/javascript src='/dir/jsfile.js'></script>
或
<script type=text/javascript src='../../scripts/jsfile.js'></script>
如果您不提供服务器/域,路径将是相对于通过主文件的路径的页面的路径或脚本