[Angular] Lazy Load CSS at runtime with the Angular CLI

Ever had the need for multiple "app themes", or even to completely dynamically load CSS based on which customer logs into your application? You could of course bundle all of the various themes into a single CSS entry file, but your application size would suffer a lot. Therefore, in this lesson we're going to have a look how to define multiple entry-level CSS files and how to "lazy load" them at runtime.

 

Source: https://egghead.io/lessons/angular-lazy-load-css-at-runtime-with-the-angular-cli

 

For example we want to lazy load two theme file: 'client-a-style.scss', 'client-b-style.scss':

In angular.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/dyncss",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": ["src/favicon.ico", "src/assets"],
            "extractCss": true,
            "styles": [
              "src/styles.scss",
              {
                "input": "src/client-a-styles.scss",
                "bundleName": "client-a",
                "inject": false
              },
              {
                "input": "src/client-b-styles.scss",
                "bundleName": "client-b",
                "inject": false
              }
            ],
            "scripts": []
          },

  

After you do `ng build --prod`, it will generate two css files: 'client-a.css' and 'client-b.css'.

Then we can do lazy load when button click:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Component, Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'dyncss';
  // reference document
  constructor(@Inject(DOCUMENT) private document: Document) {}
 
  loadStyle(styleName: string) {
    // get head
    const head = this.document.getElementsByTagName('head')[0];
 
    // create link tag to load css
    let themeLink = this.document.getElementById(
      'client-theme'
    ) as HTMLLinkElement;
    if (themeLink) {
      // if the link is already exist, we just replace the link source
      themeLink.href = styleName;
    } else {
      // if link doesn't exist, we create link tag
      const style = this.document.createElement('link');
      style.id = 'client-theme';
      style.rel = 'stylesheet';
      style.href = `${styleName}`;
 
      head.appendChild(style);
    }
  }
}
1
2
3
4
5
6
<button type="button" (click)="loadStyle('client-a.css')">
  Load client style a
</button>
<button type="button" (click)="loadStyle('client-b.css')">
  Load client style b
</button>

  

posted @   Zhentiw  阅读(1468)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-08-22 [Java Spring] Spring Annotation Configuration Using XML
2018-08-22 [Jest] Automate your migration to Jest using codemods
2017-08-22 [D3] Reuse Transitions in D3 v4
2016-08-22 [React] Styling React Components With Aphrodite
2016-08-22 [Canvas] Make Canvas Responsive to Pixel Ratio
2016-08-22 [RxJS] Introduction to RxJS Marble Testing
2015-08-22 [Node.js] Web Scraping with Pagination and Advanced Selectors
点击右上角即可分享
微信分享提示