[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:
"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:
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);
}
}
}
<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>
最新文章
- 关于JQ toggle 的注意事项
- @Scheduled 注解
- 在C#中如何读取枚举值的描述属性
- Kali Linux 2016.2发布提供虚拟机以及系统镜像下载
- hiho_1049 二叉树遍历
- 如何编写一个编译c#控制台应用程序的批处理程序
- 用c++库函数轻松解决回文问题
- (转载)C# 编程 使用可空类型
- Java疯狂讲义
- Android开发之导入错误
- Java重写equals()和hashCode()
- MongoDb进阶实践之三 MongoDB查询命令详述
- 常用SQL Server命令(持续) | Commonly used SQL Server command list (Cont&#39;)
- [PHP] 魔术方法__get __set __sleep __wakeup的实际使用
- 报表工具highcharts使用心得
- 《DOM Scripting》学习笔记-——第五章、第六章 案列改进
- [20171120]11G关闭直接路径读.txt
- Revit api 创建楼梯图元
- SQL语句操作优先级顺序
- C# SQLite数据库操作