javascript - 函数调用中的延迟加载要求语句?
问题描述
我需要将以下内容重构为延迟加载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 一次fire
或fire2
执行?
解决方案
您可以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
推荐阅读
- javascript - 删除字符串中的 Unicode 字符 (JS)
- python - 来自“pip install quantecon”的语法错误
- python - Comparing Numpy Arrays
- java - java-server websocket failed: Error during WebSocket handshake: Unexpected response code: 404
- javascript - 带对数刻度的 H 轴日期(谷歌图表)
- c++ - D3DXMatrixRotationAxis 旋转错误的轴
- java - 导出 jar 时 Files.copy 返回空文件
- css - 引导程序 3.3.7 与引导程序 4
- c++ - 错误:A 类不是 B 类 C++ 的基础
- python-3.x - How to scrape a JavaScript website using Python with Selenium