在JavaScript中,获取当前脚本的路径可以通过多种方式,以下是一些常见的方法:
document.currentScript
属性(适用于内联脚本和动态加载的脚本)if (document.currentScript) {
var scriptPath = document.currentScript.src;
console.log(scriptPath);
} else {
console.log('无法获取当前脚本路径');
}
<script>
标签的src
属性(适用于已加载的脚本)如果你知道脚本的ID或其他标识符,可以通过DOM操作获取脚本路径:
<script id="myScript" src="/path/to/script.js"></script>
var script = document.getElementById('myScript');
if (script) {
var scriptPath = script.src;
console.log(scriptPath);
} else {
console.log('无法找到指定的脚本元素');
}
import.meta.url
(适用于ES模块)在ES模块中,可以使用import.meta.url
来获取当前模块的URL,然后通过URL解析出路径:
if (import.meta.url) {
var scriptPath = new URL('.', import.meta.url).pathname;
console.log(scriptPath);
} else {
console.log('无法获取当前模块路径');
}
在某些情况下,可以通过捕获错误并解析堆栈信息来获取脚本路径:
try {
throw new Error();
} catch (e) {
var stackLines = e.stack.split('\n');
for (var i = 0; i < stackLines.length; i++) {
if (stackLines[i].indexOf('script.js') !== -1) {
var scriptPath = stackLines[i].trim().split(' ')[1];
console.log(scriptPath);
break;
}
}
}
document.currentScript
和import.meta.url
提供了较为准确的脚本路径信息。document.currentScript
在某些旧版浏览器中可能不支持。通过以上方法,你可以根据具体需求选择合适的方式来获取当前脚本的路径。
领取专属 10元无门槛券
手把手带您无忧上云