【发布时间】:2021-09-22 12:13:36
【问题描述】:
我正在通过桌面(最新的 Chrome)和移动(带有 iOS 14.6 的 Safari)试验 Javascript 模块,我的代码在桌面(标准浏览器或移动仿真模式)上完美运行,但在我的 iPhone 上失败了。根据https://caniuse.com/?search=modules,尽管自Safari iOS 11 起支持,但使用<script type="module"> 导入的JS 代码根本无法执行
下面的测试代码改编自 How to serve ES6 modules on Safari? ,托管在我的本地网络中的网络服务器上,移动和桌面客户端均可访问。对于移动调试,我使用https://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/ 的本地复制版本在移动设备上呈现console.log 命令。
test_ios.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
console.log("Start of test_ios.html...");
</script>
<title>TESTS IOS</title>
<script src="/static/hnl.mobileConsole.1.3.js"></script>
<script nomodule src="/static/fallback.js"></script>
<script type="module">
console.log("Starting the main script.");
// The following line seems to cause an error in Safari only
import { TestClass } from './static/test_module.js';
// The rest is not executed due to the error
let test_class = new TestClass;
console.log("Done.");
</script>
<script>
console.log("End of test_ios.html...");
</script>
<body>
</body>
</html>
/static/test_module.js
export class TestClass {
constructor() {
console.log("Created a test class in test_module.js");
document.body.append("test_module.js");
}
}
/static/fallback.js
console.log("Fallback.js");
document.body.append("Fallback");
桌面上的结果,如预期的那样
测试字符串test_module.js 被写入网页,控制台中有以下几行:
--==## Mobile Console v1.3.5 active ##==--
End of test_ios.html...
Starting the main script.
Created a test class in test_module.js
Done.
iOS 14 上的结果 - 模块 JS 和后备均未执行
页面是空白的(没有执行document.body.append(...))并且控制台中只有以下几行:
--==## Mobile Console v1.3.5 active ##==--
End of test_ios.html...
已完成进一步检查:
- 我嗅探了网络,发现移动设备请求了
/static/test_module.js(没有请求fallback.js)。 - 网络服务器返回的
/static/test_module.js的内容类型似乎是一致的 (application/javascript; charset=utf-8)。 - 将
test_module.js重命名为test_module.mjs没有帮助(结果与上述相同)
【问题讨论】:
标签: javascript ecmascript-6 mobile-safari es6-module-loader