我正在尝试执行类似C #include "filename.c"
或PHP include(dirname(__FILE__)."filename.php")
的操作,但是在javascript中。我知道如果我可以从URL加载一个js文件(例如标签的src属性中给出的URL),我就可以这样做。有什么方法可以让javascript知道吗?
或者,有没有什么好方法可以从同一个域动态加载javascript(具体不知道域名)?例如,假设我们有两个相同的服务器(QA和生产),但它们显然具有不同的URL域。有没有办法像my include("myLib.js");
那样myLib.js将从加载它的文件的域加载?
对不起,如果那些措辞有些混乱。
答案 0 :(得分:77)
在剧本中:
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
这是有效的,因为浏览器按顺序加载和执行脚本,因此当您的脚本执行时,它所包含的文档肯定会将您的脚本元素作为页面上的最后一个。这段代码当然必须是脚本的“全局”代码,因此请将src
保存在以后可以使用的地方。通过将全局变量包装在:
(function() { ... })();
答案 1 :(得分:40)
除Internet Explorer(任何版本)之外的所有浏览器都有document.currentScript
,它始终有效(无论文件包含的方式如何(async,bookmarklet等))。
如果您想知道您现在所处的JS文件的完整网址:
var script = document.currentScript;
var fullUrl = script.src;
Tadaa。
答案 2 :(得分:16)
如果您的文档中有内联脚本,则此处接受的答案不起作用。为避免这种情况,您可以使用以下内容仅定位具有<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模板中遇到的一些问题。
答案 3 :(得分:7)
我刚刚做了这个小技巧:
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()())
处理:Chrome,Firefox,Edge
尽情享受!
答案 4 :(得分:5)
根据这里找到的答案,我想出了以下内容:
<强> 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;
答案 5 :(得分:4)
我最近发现了一种更清晰的方法,可以随时执行,而不是在脚本加载时强制同步执行。
使用stackinfo在当前位置获取堆栈跟踪,并从堆栈顶部获取info.file
名称。
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
答案 6 :(得分:2)
我编写了一个简单的函数,它允许使用try / catch方法获取当前javascript文件的绝对位置。
你可以看到它here。
答案 7 :(得分:1)
我可能误解了你的问题,但只要生产和开发服务器使用相同的路径结构,你就应该能够使用相对路径。
<script language="javascript" src="js/myLib.js" />
答案 8 :(得分:1)
参考此处找到的答案
getCurrentScript and getCurrentScriptPath
我想出了以下几点:
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScript = function () {
if ( document.currentScript && ( document.currentScript.src !== '' ) )
return document.currentScript.src;
var scripts = document.getElementsByTagName( 'script' ),
str = scripts[scripts.length - 1].src;
if ( str !== '' )
return src;
//Thanks to https://stackoverflow.com/a/42594856/5175935
return new Error().stack.match(/(https?:[^:]*)/)[0];
};
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScriptPath = function () {
var script = getCurrentScript(),
path = script.substring( 0, script.lastIndexOf( '/' ) );
return path;
};
答案 9 :(得分:0)
无论是脚本,html文件(例如框架),css文件,图像等等,如果你不指定服务器/域html doc的路径将是默认值,因此您可以这样做,例如,
<script type=text/javascript src='/dir/jsfile.js'></script>
或
<script type=text/javascript src='../../scripts/jsfile.js'></script>
如果您不提供服务器/域,则路径将相对于页面路径或主文档路径的脚本
答案 10 :(得分:0)
function getCurrnetScriptName() {
const url = new URL(document.currentScript.src);
const {length:len, [len-1]:last} = url.pathname.split('/');
return last.slice(0,-3);
}