Search code examples
angularionic-frameworkionic4

How to eagerly load ion-modal in Angular 10


Just to be clear, I don't believe this issue is at all related to routing lazy-loading because this issue is in a bootstrapped component where this is failing to run as expected.

I have an ion-modal that is triggered from the base app.component for when no network is detected. I need to ensure that the ion-modal scripts are available after the initial payload is sent; however, when I load the app then turn off the network in the network debugger tab it is lazy-loading ion-modal. vendor.js:41664 ChunkLoadError: Loading chunk 20 failed.

The script being referenced has the following in its webpack comments and appears to be entirely ion-modal code. ./node_modules/@ionic/core/dist/esm/ion-modal.entry.js

If I trigger a modal to show then hide, the chunk is successfully loaded and the following network error modal works as expected when triggered in the network debugger. When I try to search for articles around eager loading it's always about routing and that is not what I am looking for here.


Solution

  • Closing the loop on this. In ionic v4.x, this isn't possible as it appears the overlay components are registered at runtime. While <ion-modal style="display:none;"> can be used with JIT-compiled templates to preload the scripts where needed, it will fail when used with AOT-compiled templates. So the solution for now is to programmatically present then dismiss a modal during the bootstrap process or as early as can be done after IonicModule is available.

      // Call this somewhere early where IonicModule has been imported, we are doing it in the app.component.ts constructor in our example
      async preloadModal() {
        let tempModal = await this.modalController.create({
          animated: false, // this should prevent it from being visible
          swipeToClose: false, // disable interaction to prevent unexpected behavior
          backdropDismiss: false, // disable interaction to prevent unexpected behavior
          showBackdrop: false, // minimize changes to UI
          keyboardClose: false, // minimize side-effects
          component: MyModalComponent, // Your custom modal component likely won't render, be sure to preload any related assets inside the index.html <head> tags
          componentProps: {
            // your component props, if needed
          }
        });
        await tempModal.present();
        await tempModal.dismiss();
      }
    

    Related github issue