我正在创建一个延迟加载的组件.我的问题是关于JavaScript本身,而不是任何特定的框架(Reaction、Svelte等),所以我给出了一些伪代码.

const myLazyLoadedComponent() {

  let myComponent
  let isLoading = true
  import('/some/path.xx').then(c => {
    myComponent = c
    isLoading = false
  })

//this part is reactive with the variables above:

  return (
    if (isLoading) <div>Loading..<div/>
    else <myComponent/>
  )
}

这将在第一次很好地发挥作用.但当我关闭-重新打开或打开它的另一个实例时,Loading..会在myComponent之前显示一微秒.

Is there a way to first check if the module was already imported, and based on that, either use it directly or async import()?

大概是这样的:

if (isAlreadyImported('/some/path.xx').) {
  import { myComponent } from '/some/path.xx'
} else {
  isLoading = true
  import('/some/path.xx').then(c => {
    myComponent = c
    isLoading = false
  })
}

推荐答案

您可以缓存组件并执行同步或异步回调:

const cache = {};
async function loadComponent(loader, cb){
   const key = loader.toString();
   if(cache[key]){
      cb(cache[key]);
      return cache[key];
   }
   cache[key] = await loader().then(m => m.default);
   cb(cache[key]);
   return cache[key];
}

...

isLoading = true;
await loadComponent(() => import('/some/path.xx'), c => (isLoading = false, myComponent = c));

Javascript相关问答推荐

React Hooks中useState的同步问题

在分区内迭代分区

警告!合同执行期间遇到错误[执行已恢复](Base Layer 2)

vscode扩展-webView Panel按钮不起任何作用

硬币兑换运行超时

仅针对RTK查询中的未经授权的错误取消maxRetries

如何使用JavaScript将文本插入空div

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何将Map字符串,布尔值转换为{key:string;value:bo布尔值;}[]?<>

jQuery s data()[storage object]在vanilla JavaScript中?'

无法使用单击按钮时的useState将数据从一个页面传递到另一个页面

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

JavaScript不重定向配置的PATH

回溯替代方式

AJAX POST在控制器中返回空(ASP.NET MVC)

FileReader()不能处理Firefox和GiB文件

如何在Jest中模拟函数

更改管线时不渲染组件的react

material UI自动完成全宽

在此div中添加一个类,并在一段时间后在Java脚本中将其删除