You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IONIC 5 如何实现页面重载过程中不出现白屏问题

问题原因分析

你出现白屏的核心原因是window.location.reload()属于全局页面重载,会销毁当前整个Ionic应用实例、重新加载所有资源初始化应用,你写的路由拦截逻辑只覆盖Angular路由内部导航的加载状态,全局重载阶段应用还没初始化完成,所以自定义loading层不会生效,就出现了1-2秒白屏。

解决方案

最优方案:放弃全局重载,改用路由刷新(彻底避免白屏)

你触发重载的需求大概率是要刷新/order页面的数据,完全不需要全局重载,只要用Ionic/Angular的路由重载逻辑即可,既不会有白屏,性能也更好:
把原来的重载代码替换成:

this.router.navigate(['/order'], {
  skipLocationChange: true,
  replaceUrl: true
}).then(() => {
  // 手动触发order页面的初始化逻辑即可,不需要全局重载
  // 如果使用Angular 14+版本,也可以搭配onSameUrlNavigation配置使用
})

额外可以在AppRoutingModule里加路由配置,支持同路由刷新:

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    onSameUrlNavigation: 'reload', // 同路由跳转时重新触发组件生命周期
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

兼容方案:如果必须要用全局重载,在index.html里加静态loading层

如果业务必须要全局刷新,那你不能把loading写在app.component里,要写在index.html的静态内容里,应用没初始化的时候也能展示:

  1. 修改src/index.html,在body里加静态loading层:
<body>
  <app-root></app-root>
  <!-- 静态全局加载层,应用初始化完成后自动隐藏 -->
  <div id="global-loading" style="position: fixed;top:0;left:0;width:100vw;height:100vh;display: flex;flex-direction: column;align-items: center;justify-content: center;background: #fff;z-index: 99999;">
    <img src="assets/icon/favicon.png" style="height:150px;width:150px;"/> <br/>
    <ion-spinner name="bubbles"></ion-spinner>&nbsp;
    <span>Please Wait..</span>
  </div>
</body>
  1. 在app.component.ts的platform.ready回调里隐藏这个静态层:
this.platform.ready().then(() => {
  // 隐藏全局静态loading层
  const globalLoading = document.getElementById('global-loading');
  if(globalLoading) globalLoading.remove();
  setTimeout(() => {
    this.splashScreen.hide();
  }, 50);
});
  1. 可以删掉原来app.component.html里写的loading层,或者保留用来做路由内部导航的加载提示。

额外修复点:当前代码的隐含问题

原来的splashScreen.hide回调里的this指向错误,要改为箭头函数避免报错:

this.platform.ready().then(() => {
  setTimeout(() => { // 改为箭头函数,保证this指向当前组件实例
    this.splashScreen.hide();
  }, 50);
});

内容的提问来源于stack exchange,提问作者Fatty Low

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:27:06