There is no doubt that we all want our applications to load very fast. To do this, we need to keep the initial bundle size small. Lazy loading is one of the methods we use in this case. We can lazy load some third-party JavaScript files and some CSS files. In this article, we will learn how to lazy load our CSS files and how to extract them with a hash on production build to prevent browser cache.

While developing ABP Commercial, we were able to load CSS files lazy, but we could not extract these CSS files to the build output with a hash. During my research, I encountered this issue and saw that the name of a CSS file that is loaded lazily cannot be hashed. The names of CSS files may not be hashed, but the names of JavaScript files can be hashed. I achieved my goal by importing JavaScript files instead of CSS files.

Image for post

Switching between ABP Lepton themes

Let’s see how this work can be done with an application that can switch between Bootswatch themes.

I downloaded the minified CSS files of MateriaJournal, and Lux themes and copied them to the src/assets/styles folder. Then I created JavaScript files corresponding to each CSS file.

Image for post

assets/styles

The content of {theme-name}.js:

import css from "./{theme-name}.min.css";

export default css;

The related CSS file has imported and exported as default in each of JavaScript files.

Let’s see how to load these JavaScript files in our application.

#webpack #lazy-loading #javascript #typescript #angular

Extracting and Hashing Lazy-Loaded CSS in Angular
9.45 GEEK