dottodot
dottodot

Reputation: 1619

How to overcome loading chunk failed with Angular lazy loaded modules

If I make changes to my angular app the chunk names will change on build and the old version will be removed from the dist folder. Once deployed, if a user is currently on the site, and then navigates to another part of the site, I get a "loading chunk failed" error because the old file is no longer there.

My app is built using Angular CLI and is packaged using webpack.

Is there any way this can be fixed?

Upvotes: 80

Views: 80758

Answers (13)

Jack A.
Jack A.

Reputation: 4443

For applications that use lazy loading, these errors typically happen either during the initial load process or during a lazy-loaded route navigation.

During initial load it can be difficult to determine the state of the application and handle the error appropriately. I'm reluctant to introduce the possibility of an infinite reload cycle in this case, so I do not attempt to automatically reload the app, just show an error message telling the user that they need to reload the page to continue.

During navigation, chunk load errors can be handled like this:

router.events
    .pipe(
        filter(evt => evt instanceof NavigationError),
        map(evt => evt as NavigationError)
    )
    .subscribe(evt => {
        if (evt.error instanceof Error && evt.error.name == 'ChunkLoadError') {
            window.location.assign(evt.url);
        }
    });

This has the advantage of seamlessly loading the desired route.

Upvotes: 8

Leroy Meijer
Leroy Meijer

Reputation: 1197

For some reason the pattern: const chunkFailedMessage = /Loading chunk [\d]+ failed/; wasn't working for me. I had to change it to: const chunkFailedMessage = /Loading chunk .*failed.*[.js\\)]/;

Below the full ErrorHandler for Angular 17+:

import { ErrorHandler, Injectable } from "@angular/core";

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    handleError(error: any): void {
        const chunkFailedMessage = /Loading chunk .*failed.*[.js\\)]/;
        if (chunkFailedMessage.test(error.message)) {
            if (confirm("New version available. Load New Version?")) {
                window.location.reload();
            }
        }
    }
}

The way I use it is as follows: so for example you have multiple tabs open of your application and in one of them you logout. In my case this meant the token was expired or invalidated (SSO). So the other tab wasn't aware of this, but because the modules were lazy-loaded and you need a valid token for that, to load modules as you go, I got this: Loading Chunk .... failed ... .js message. In the application a notification is showed and user is sent to the login page.

Upvotes: 0

Darren Shewry
Darren Shewry

Reputation: 10410

If the Angular application is in an unrecoverable state, the Angular docs suggestion is to subscribe to the Service Worker's unrecoverable updates/events then handle by what makes sense to your app.

e.g. reload the page, or notify the user, etc:

@Injectable()
export class HandleUnrecoverableStateService {
  constructor(updates: SwUpdate) {
    updates.unrecoverable.subscribe(event => {
      notifyUser(
        'An error occurred that we cannot recover from:\n' +
        event.reason +
        '\n\nPlease reload the page.'
      );
    });
  }
}

i.e. the current version of the user's app has a reference to a file not in the cache and not accessible from the web server, which is typically what happens in this Chunk Load error scenario.

Upvotes: 6

OutstandingBill
OutstandingBill

Reputation: 2844

TL;DR use npm run ... to serve your app, not ng serve ...

I was getting this error ...

screenshot of error

 Error: Uncaught (in promise): ChunkLoadError: Loading chunk default-projects_app3-orders_src_app_order_order_component_ts failed.
(error: http://localhost:4205/default-projects_app3-orders_src_app_order_order_component_ts.js)
__webpack_require__.f.j@http://localhost:4205/remoteOrders.js:50599:29

... while going through a module federation worked example. Turned out I wasn't serving the various bits correctly. I had read the scripts section of package.json...

  "scripts": {
...
    "start:app1": "ng serve",
    "start:app2": "ng serve app2-restaurant",
    "start:app3": "ng serve app3-orders",
...
  }

... and wrongly assumed I could just run ng serve, etc. at the command line.

Once my colleague pointed out I should instead run npm run start:app1, etc., it started working properly.

Upvotes: 0

Luke Kroon
Luke Kroon

Reputation: 1103

UPDATED SOLUTION BELOW Preferred solution is converting to PWA


I had the same problem and found a pretty neat solution that is not mentioned in the other answers.

You use global error handling and force app to reload if chunks failed.

import {ErrorHandler, Injectable} from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  
  handleError(error: any): void {
   const chunkFailedMessage = /Loading chunk [\d]+ failed/;

    if (chunkFailedMessage.test(error.message)) {
      window.location.reload();
    }
    console.error(error);
  }
}

It is a simple solution and here (Angular Lazy Routes & loading chunk failed) is the article I got it from.


EDIT: Convert to PWA

Another solution can be to convert your Angular site to a PWA (Progressive Web App). What this does is add a service worker that can cache all your chunks. Every time the website is updated a new manifest file is loaded from the backend, if there are newer files, the service worker will fetch all the new chunks and notify the user of the update.

Here is a tutorial on how to convert your current Angular website to a PWA. Notifying the user of new updates is as simple as:

import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Injectable()
export class PwaService {
  constructor(private swUpdate: SwUpdate) {
    swUpdate.available.subscribe(event => {
      if (askUserToUpdate()) {
        window.location.reload();
      }
    });
  }
}

Upvotes: 56

Luis Guilherme
Luis Guilherme

Reputation: 9

Good Morning! I had the same problem when assembling the application using angular 11. To solve it, just run as follows.

"ng build --named-chunks"

Upvotes: 0

devXd
devXd

Reputation: 205

You can use custom GlobalErrorHandler in your application, All it does is just check the error message if it has a Loading chunk [XX] failed, and forces the app to reload and load the new fresh chunks.

Create globalErrorHandler with the following code

import { ErrorHandler, Injectable } from "@angular/core";
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    handleError(error: any): void {
        const chunkFailedMessage = /Loading chunk [\d]+ failed/;
        if (chunkFailedMessage.test(error.message)) {
            if (confirm("New version available. Load New Version?")) {
                window.location.reload();
            }
        }
    }
}

After creating globalErrorHandler.ts, you should define the ErrorHandler in app.module.ts

@NgModule({
  providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})

Upvotes: 11

Jimmy Kane
Jimmy Kane

Reputation: 16825

You can also use service workers to detect the change with "polling/intervals" and inform the user for an app update.

https://angular.io/guide/service-worker-getting-started

The service worker can detect every 1minutes for example if there are new "assets/your app" and do a slide up to inform the user to reload the page or even force it if you want to.

Upvotes: 1

Drake
Drake

Reputation: 19

Use Pre-Loading. You get the benefits of lazy loading, without the hassle it causes in situations like this. All of the chunks will be given to the user as fast as possible without slowing down the initial load time. Below is an excerpt from https://vsavkin.com/angular-router-preloading-modules-ba3c75e424cb to explain how it works (see the article for diagrams):

First, we load the initial bundle, which contains only the components we have to have to bootstrap our application. So it is as fast as it can be.

Then, we bootstrap the application using this small bundle.

At this point the application is running, so the user can start interacting with it. While she is doing it, we, in the background, preload other modules.

Finally, when she clicks on a link going to a lazy-loadable module, the navigation is instant.

We got the best of both worlds: the initial load time is as small as it can be, and subsequent navigations are instant.

Upvotes: -1

Olajire Dominic
Olajire Dominic

Reputation: 3

Clear Browser cache. Worked for me

Upvotes: -13

terodox
terodox

Reputation: 37

I know I'm a little late to the game on this questions, but I would recommend changing your deployment approach.

Check out https://immutablewebapps.org/. The basic philosophy is to isolate you build time assets from your runtime variables. This provides a bunch of benefits, but the biggest are:

  • No caching problems for assets because they are isolated at the route level
  • The same code that was vetted in development is used in production
  • Instant fallback with hot cache for consumers in the case of a problem
  • Chunks that are created are maintained for previous version isolated by routes avoiding the active deployment vs active user problem

This also should not interfere with the ** PreloadAllModules** suggestion offered by @dottodot below.

Upvotes: 2

Ulfius
Ulfius

Reputation: 617

I keep my old chunks in place for a couple days after an update for just this purpose. My app also consists of mini-SPAs, so as they move around, they're likely to pick up the new version during a page load.

Upvotes: 4

Lovepreet Singh
Lovepreet Singh

Reputation: 19

You can send some event from server side to reload the application. Also there is option to pre fetch the lazy modules in background so as to prefetch them as soon as possible instead of waiting for the request of that modules.

Upvotes: -1

Related Questions