【问题标题】:ES6 module fails on Safari mobile (iOS14.6)ES6 模块在 Safari mobile (iOS14.6) 上失败
【发布时间】: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...

已完成进一步检查:

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

【问题讨论】:

    标签: javascript ecmascript-6 mobile-safari es6-module-loader


    【解决方案1】:

    我发现了问题:只要调用了console.log,以下库就破坏了 Mobile Safari 中的 JS 执行:

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

    删除此库包含或/并将所有对 console.log 的调用替换为 alert 使上述代码按预期工作。示例代码还存在一些小错误(例如,没有 &lt;/head&gt; 关闭),但这不是根本问题。

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

    下次遇到 Mobile Safari 问题时的要点:在您的 JS 代码中添加警告框以查看它何时/何​​处中断:(

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 2013-09-09
      • 2018-01-29
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      相关资源
      最近更新 更多