javascript - 如何使加载屏幕运行直到所有图像都加载完毕?
问题描述
我尝试在等待所有图像完全加载时制作加载屏幕。React 生命周期是渲染 -> componentDidMount -> 渲染,我的图像没有完全加载,刚刚被调用,但我componentDidMount
总是完成并执行渲染,即使我的图像没有完全加载。
componentDidMount() {
const ie = [document.querySelectorAll('img')];
ie.map(imgElm => {
for (const img of imgElm) {
if (!img.complete) {
this.setState({ imageIsReady : true});
}
}
return this.setState({ imageIsReady : false});
})
}
在componentDidMount
for循环功能上尝试检查每个img是否完整,给我一百true
(我的图像很多,只是尝试制作画廊)。和加载屏幕显示,但只有几毫秒,然后我可以滚动我的图像,但我的图像的一半以上仍在加载。
render() {
<div>
{
this.state.imageIsReady ?
<div className='inset-0 fixed flex justify-center z-20 w-full h-full bg-black bg-opacity-25 blur'>
<img src={loading} className='w-3/12' alt="load"/>
</div> :
<div className='hidden '>
<img src={loading} alt="load"/>
</div>
}
<div>page......</div>
</div>
}
我的代码:httpssetTimeout
://alfianahar.github.io/MobileLegendHeroList/ 在我使用的这个站点中componentDidMount
,这并不能解决我使用慢速 3g 或快速 3g/ 时的问题
解决方案
也许这个例子可以帮助你。但请记住,这仅适用于未嵌套在组件内的图像。
class Component extends Component {
constructor(props) {
super(props)
this.state = {
ready: false
}
}
componentDidMount() {
Promise.all(
Array.from(document.images)
.filter(img => !img.complete)
.map(img => new Promise(
resolve => { img.onload = img.onerror = resolve; }
))).then(() => {
this.setState({ ready: true })
});
}
render() {
if ( ! this.state.ready ) return <div>Loader</div>
return <div>Content</div>
}
}
<Container>
<img/> <!-- work -->
<Component>
<img/> <!-- doesn't work -->
</Component>
</Container>
推荐阅读
- date - SAP Business Objects Min Date for each ID
- reactjs - React grid layout not working with firebase
- haskell - Compile Haskell program with third-party dependencies
- java - How Do I Mark A RequestParam As Optional In Swagger?
- python - "module 'torchtext.data' has no attribute 'Field'"
- javascript - how to call a function with a submit element
- android - HDR gradient on Android not possible?
- math - 将平面转换为 XY 平面
- sql - 获取 Time 的每日行数
- entity-relationship - 具有两个参与者的 ER 建模帐户交易