如何检测浏览器中脚本是作为ES module导入还是普通script标签加载?
运行时检测脚本加载模式的实现方案
可以实现运行时的加载模式检测,浏览器环境下有几种成熟的判断方案,可根据你的兼容需求选择:
方案1:检测import.meta对象(推荐,兼容现代浏览器)
ES Module 运行环境会内置import.meta元信息对象,普通非module类型的script标签运行时不存在该对象,直接判断即可:
if (typeof import.meta !== 'undefined') { // 对应 ES Module 被 import 引入的场景 console.log('当前为 ES Module 加载模式') } else { // 对应普通 <script> 标签加载的场景 console.log('当前为普通 script 标签加载模式') }
兼容范围:Chrome 63+、Firefox 62+、Safari 11.1+,覆盖95%以上的全球用户量
方案2:检测document.currentScript值
普通script标签同步执行时,document.currentScript会指向当前运行的script DOM节点;而ES Module 环境下该值固定为null:
if (document.currentScript === null) { // ES Module 加载模式 } else { // 普通 script 标签加载模式 }
注意:该方案存在边缘case例外:如果普通script是动态插入、或者带async/defer属性加载,部分场景下document.currentScript也会返回null,建议和其他方案组合使用
方案3:全局挂载兜底判断
如果你的脚本本身需要对外暴露方法,也可以用全局变量挂载的逻辑做兜底:
// 脚本核心逻辑 const yourScriptUtils = { run: () => console.log('脚本执行') } // ES Module 导出逻辑 if (typeof export !== 'undefined') { export default yourScriptUtils } else { // 普通script场景下挂载到window全局对象 window.yourScriptUtils = yourScriptUtils }
如果需要100%的判断准确率,可以把前两个方案组合判断:同时满足typeof import.meta !== 'undefined'和document.currentScript === null时,才判定为ES Module加载模式即可。
内容的提问来源于stack exchange,提问作者Simone
相关产品推荐
相关产品推荐

