Using preloading in Angular apps to reduce ChunkLoadingError

Reducing the amount of ChunkLoadingError

Ali Kamalizade

--

Photo by Mike van den Bos on Unsplash

Our Angular-based frontend is divided into different self-contained modules (e.g. inbox, document center, dashboard…). Those modules are typically rather small and loaded asynchronously. The benefits of splitting up the application into modules:

  • Avoid loading stuff of pages you’re not visiting
  • Initial loading times are improved as we only load the necessary code initially
  • The modules are being kept as small as possible which makes it easier to work on a particular area without affecting other product areas

When a new deployment is published in production all these modules get a hash. This prevents browsers to cache old versions of code which changes frequently (as the hash is different every time the browser will download the new modules instead of the cached modules from the past). New modules in, old modules out. This is great for static pages but …

How does this affect single page applications? Well, as long as we do not reload the page the references to the old modules are still there. If we now attempt to navigate to one of those unloaded modules, the browser attempts to load a JavaScript bundle (aka file) which may not exist anymore depending on your web hosting platform (e.g. Netlify). In case the bundle does not exist anymore Angular will throw a ChunkLoadError exception. The only thing a user can do is to reload the page but this sours the user experience.

ChunkLoadError exception

Solution: preloading. The idea: if the user is logged in we load the modules silently in the background after a delay. Benefits:

  • Initial loading are still as good as before as we only load the necessary code initially for bootstrapping the application
  • Switching to other pages for the first time is a bit faster as the modules might have already been loaded
  • Greatly reduced chance of having the ChunkLoadError exception again

--

--

Ali Kamalizade

Co-founder of Sunhat. Posts about software engineering, startups and anything else. 有難うございます。🚀