Loading chunk failed with angular lazy loaded modules

I get a “loading chunk failed” .Is there any way this can be fixed?

1 Like

When we deploy a new version of an app, we often encounter with loading chunks failed issue. It happens because the new version has new hashed name JS files but the browser is loading the non-existent previous version files.

If a user has already opened the application in the browser, and at the same time deploys a new build, then navigates to a route whose chunk was never cached, the browser shows the loading chunk failed error. It is because the current file version is trying to fetch that hashed name chunk file from the server which is now replaced with another name due to a new build.

To fix this, We can use global error handling and force the app to reload if chunks failed.

For this, we need to create a GlobalErrorHandler class that implements an ErrorHandler class. 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.

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

Since we created a custom GlobalErrorHandler, we need to provide it in our root module to change the default behavior in our app, so instead of using the default ErrorHandler class, we are using our custom GlobalErrorHandler class.

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

2 Likes