【问题标题】:Long load using ES6 modules in Chrome在 Chrome 中使用 ES6 模块进行长时间加载
【发布时间】:2018-09-13 09:06:26
【问题描述】:

我的 javascript 应用程序适用于自助服务终端,并且仅针对 Chrome 浏览器。我正在使用 Chrome 版本 65。我正在尝试使用 ES6 模块而不使用像 Babel 这样的转译器。我的代码原来是:

在 index.html 中:

<script src="js/index.js"></script>

index.js:

import Main from './classes/Main.js';

const init = () => {
  const app = new Main();
};

init();

Main.js:

export default class Main {
  constructor() {
  }
}

最初我从 index.js 第 1 行收到错误“Uncaught SyntaxError: Unexpected identifier”。然后基于ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier",我在 html 标签中添加了 'type="module"':

<script type="module" src="js/index.js"></script>

这确实加载了,但根据网络分析器,我的浏览器加载 index.js 和 main.js 大约需要 15 秒。会发生什么?

【问题讨论】:

    标签: javascript es6-modules es6-class


    【解决方案1】:

    所以我在本地机器上运行了一些测试。我有一个运行以下三个文件的简单 NodeJs 服务器:

    index.html

    <!doctype html>
    <html>
    <head>
      <title>es6 Module test</title>
      <script>
      console.time('load module');
      console.time('time until constructor called');
      </script>
      <script type="module" src="module.js"></script>
      <script>
      console.timeEnd('load module');
      </script>
    </head>
    <body>
      See console output.
    </body>
    </html>
    

    module.js

    import Main from './Main.js';
    
    const init = () => {
      const app = new Main();
    };
    
    init();
    

    Main.js

    export default class Main {
      constructor() {
        console.timeEnd('time until constructor called');
      }
    }
    

    在 Chrome 65 中运行此代码(在 Mac 上)

    我得到以下输出:

    运行 1

    load module: 0.141845703125ms
    time until constructor called: 7.90087890625ms
    

    运行 2

    load module: 0.139892578125ms
    time until constructor called: 6.5498046875ms
    

    运行 3

    load module: 0.160888671875ms
    time until constructor called: 7.14404296875ms
    

    运行 4

    load module: 0.297119140625ms
    time until constructor called: 7.4228515625ms
    

    这三个文件的下载时间都在 2 毫秒到 10 毫秒之间。

    我真的不知道为什么你的时间慢了这么多。但他们不应该。也许您的服务器受到重创,无法足够快地响应?

    可能需要检查的事项:

    如果您尝试从地址栏下载每个文件,会发生什么情况?他们仍然需要很长时间才能下载吗?

    在不同的服务器上呢?

    【讨论】:

    • 这些都是很好的建议。我会试一试并报告。
    【解决方案2】:

    我在使用以下方式提供文件时遇到了同样的问题:

    python -m SimpleHTTPServer
    

    改用 python3 http.server 后,问题解决了:

    python3 -m http.server
    

    【讨论】:

    • 太棒了!虽然奇怪的错误。我改用 npx 服务,一切正常
    • 这并没有为我解决问题。事实上,通过将其传播到 HTML 文件,它变得更糟(在 Windows 10 上通过 WSL 运行)。 :\
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2015-03-16
    • 2016-09-02
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多