我正在创建一个延迟加载的组件。我的问题是关于 JavaScript 本身,而不是任何特定的框架(React、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 之前显示一微秒。
有没有办法先检查模块是否已经导入,然后基于此,直接使用它还是异步导入()?
类似这样的:
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];
}
return cache[key] = await loader().then(m => m.default);
}
...
isLoading = true;
await loadComponent(() => import('/some/path.xx'), c => (isLoading = false, myComponent = c);