Angular Lazy Routes & loading chunk failed

Kamran Khatti
2 min readJul 2, 2019

--

Angular’s lazy loading feature is a design pattern that loads NgModules as needed, which splits build file into many chunks and load on demand to speed up page. For large app which has lots of routes use lazy loading, which helps keep initial bundle size smaller that decrease load time.

Using lazy loading may happens you to face an odd issue “Loading chunk [number] failed” on navigating any route and this is the issue which we gonna address and find solution and fix it.

Error: Uncaught (in promise): Error: Loading chunk 0 failed.

By default browser cached the HTML and CSS/JS chunks on initial load to speed up app by loading from cache instead of making network call.

If we further debug we find that if any user who already opened app in browser, and we got new build deploy if that user tries to navigate route loading chunk failed issue occurs, because browser is using already cached chunks instead of newly deployed.

So the culprit is browser cache, if we hard refresh (control + shift + R) page after new build deploy to load new chunks everything works fine, all we need to either show a popup message to user and ask him to reload page or we programmatically force app to reload if chunks failed error occurs.

To solve this, we use global error handling and force app to reload if chunks failed.

We created a custom GlobalErrorHandler class which implements ErrorHandler, all it do just check the error message if it has Loading chunk [number] failed we force app to reload to load the new fresh chunks.

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

We can also show an alert message asking user to manually reload page.

--

--