B T*_*B T 57 javascript include absolute-path src
我正在尝试做一些类似C #include "filename.c"或PHP的东西,include(dirname(__FILE__)."filename.php")但是在javascript中.我知道我可以这样做,如果我可以从URL加载一个js文件(例如标签的src属性中给出的URL).有什么方法可以让javascript知道吗?
或者,是否有任何好方法从同一个域动态加载JavaScript(不知道具体的域)?例如,假设我们有两个相同的服务器(QA和生产),但它们显然具有不同的URL域.有没有办法做一些像include("myLib.js");myLib.js将从加载它的文件的域加载?
对不起,如果那有点令人困惑.
Inf*_*oop 79
在脚本中:
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为浏览器按顺序加载和执行脚本,因此当您的脚本执行时,它所包含的文档肯定会将您的脚本元素作为页面上的最后一个.这个代码当然必须是脚本的"全局",所以请保存src在以后可以使用它的地方.通过将全局变量包装在以下内容来避免泄漏:
(function() { ... })();
Run Code Online (Sandbox Code Playgroud)
Rud*_*die 46
除Internet Explorer(任何版本)之外的所有浏览器都有document.currentScript,它始终有效(无论文件是如何包含的(异步,书签等)).
如果您想知道您现在所处的JS文件的完整URL:
var script = document.currentScript;
var fullUrl = script.src;
Run Code Online (Sandbox Code Playgroud)
Tadaa.
Kev*_*ary 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, '' );
}
Run Code Online (Sandbox Code Playgroud)
这有效地捕获了最后一个外部.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()())
Run Code Online (Sandbox Code Playgroud)
工作:Chrome,Firefox,Edge
请享用 !
我最近发现了一种更简洁的方法,它可以随时执行,而不是在脚本加载时被迫同步执行。
使用stackinfo获取当前位置的堆栈跟踪,并info.file从堆栈顶部获取名称。
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
Run Code Online (Sandbox Code Playgroud)
根据这里找到的答案,我想出了以下内容:
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;
Run Code Online (Sandbox Code Playgroud)
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
Run Code Online (Sandbox Code Playgroud)
顺便说一句:我正在使用CommonJS 模块格式并与webpack捆绑在一起.