首页 > 解决方案 > 函数调用中的延迟加载要求语句?

问题描述

我需要将以下内容重构为延迟加载LargeImport

const LargeImport = require('large-import');
const useLargeImport = new LargeImport();

const MyModule = {
    init: function(){
        if(something) {
            this.fire()
        } else {
            this.fire2()
        }
    },
    fire: function(){
        useLargeImport.doSomething();

    },
    fire2: function(){
        useLargeImport.doSomethingElse();
    }
}

module.exports = MyModule;

如何仅在客户端上加载下载 LargeImport 一次firefire2执行?

标签: javascript

解决方案


您可以import在任何本机事件上使用异步。async记得在函数开头添加关键字

 <button
    onClick={async () => {
      await import("./child.js");
    }}
  >
    click
 </button>

您的代码可以更新为

fire: async function(){
 useLargeImport.doSomething();
 await import("./child.js");
},

演示代码框链接 - https://codesandbox.io/s/xenodochial-browser-tnrtj


推荐阅读