在浏览器中运行的javascript中获取当前脚本uri,如https://stackoverflow.com/a/57364525/3102264,代码是
let currentPath = import.meta.url.substring(0, import.meta.url.lastIndexOf("/"));
这在现在的浏览器上工作正常,但是在旧浏览器上它会引发语法错误。
我想检测是否支持
import.meta
,以便在 location.href 不可用时使用它。
我尝试使用 try catch 之类的
let currentPath;
try {
currentPath = import.meta.url.substring(0, import.meta.url.lastIndexOf("/"));
}
catch(e) {
currentPath = location.href.substring(0, location.href.lastIndexOf("/"));
}
但这不起作用,它仍然会抛出
未捕获的语法错误意外的令牌导入
有没有办法根据
import.meta
支持制作条件代码?
直接import.meta
中始终是语法错误。eval()
True:
import.meta
仅限于模块代码,而 eval()
在脚本上下文中执行。
由于语法错误的解析时间性质,依赖于
import.meta
支持的条件代码直接在浏览器中实现相当棘手。
另一种方法可能涉及使用单独的脚本文件:
import.meta
。location.href
。然后根据功能检测或用户代理嗅探动态加载适当的脚本。
例如,在您的 HTML 中:
<script src="feature-detection.js"></script>
在
feature-detection.js
:
if (typeof import === 'function') {
// Load module script that uses import.meta
const script = document.createElement('script');
script.type = 'module';
script.src = 'module-script.js';
document.head.appendChild(script);
} else {
// Load fallback script that uses location.href
const script = document.createElement('script');
script.src = 'fallback-script.js';
document.head.appendChild(script);
}
在
module-script.js
:
let currentPath = import.meta.url.substring(0, import.meta.url.lastIndexOf("/"));
// rest of your code
在
fallback-script.js
:
let currentPath = location.href.substring(0, location.href.lastIndexOf("/"));
// rest of your code
这样,您就可以隔离
import.meta
工作或失败的上下文,从而完全避免语法错误。