ES6 模块在 Safari 移动版 (iOS14.6) 上无法正常工作



我正在通过桌面(最新的Chrome)和移动设备(带有iOS 14.6的Safari)尝试Javascript模块,我的代码在桌面(标准浏览器或移动仿真模式)上运行良好,但在iPhone上失败。根据 https://caniuse.com/?search=modules,尽管从Safari iOS 11开始就支持使用<script type="module">导入的JS代码根本无法执行

下面的测试代码改编自如何在 Safari 上提供 ES6 模块?,托管在我的本地网络中的网络服务器上,移动和桌面客户端都可以访问。对于移动调试,我使用本地复制的 https://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/版本在移动设备上呈现控制台.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>

/静态/test_module.js

export class TestClass {
constructor() {
console.log("Created a test class in test_module.js");
document.body.append("test_module.js");
}
}

/静态/回退.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...

已经完成的进一步检查:

  1. 嗅了网络,我看到移动设备请求/static/test_module.js(没有请求fallback.js)。
  2. Web服务器返回的/static/test_module.js内容类型似乎是一致的(application/javascript; charset=utf-8)。
  3. test_module.js重命名为test_module.mjs无济于事(结果与上述相同)

我发现了问题:以下库在调用console.log后立即破坏了移动 Safari 中的 JS 执行:

<script src="/static/hnl.mobileConsole.1.3.js"></script>

删除此库包含或/并通过alert替换所有对console.log的调用,使上面的代码按预期工作。示例代码还具有小错误(例如,没有</head>关闭),但这不是根本问题。

我检查了jshint是否会在 ES6 模式下捕获它,不幸的是没有成功。

下次在移动野生动物园出现问题时要点:用警报框乱扔你的JS代码,看看它何时/在哪里破坏:(

最新更新