ProductPromotion
Logo

Angular.JS

made by https://0x3d.site

GitHub - push-based/ngx-fast-svg: 📦 SVGs, fast and developer friendly in Angular
📦 SVGs, fast and developer friendly in Angular. Contribute to push-based/ngx-fast-svg development by creating an account on GitHub.
Visit Site

GitHub - push-based/ngx-fast-svg: 📦 SVGs, fast and developer friendly in Angular

GitHub - push-based/ngx-fast-svg: 📦 SVGs, fast and developer friendly in Angular

ngx-fast-svg

Fast SVG's for Angular powered by browser native features with best performance practices and DX in mind.

Why another SVG lib for Angular?

Current implementations of SVG handling in the Browser lacks of awareness of performance.

This library covers next aspects that developers should consider for their projects:

  • Image loading performance
  • Initial rendering performance and runtime performance
  • SVG reusability
  • Optimized bundle size
  • SSR
  • Edge ready (only edge safe APIs are used)

Getting started

Install

npm install @push-based/ngx-fast-svg --save
# or
yarn add @push-based/ngx-fast-svg

Setup

Setup the library in your standalone application:

main.ts

import { provideFastSVG } from '@push-based/ngx-fast-svg';

bootstrapApplication(AppComponent, {
  providers: [
    // ... other providers
    provideFastSVG({
      url: (name: string) => `path/to/svg-assets/${name}.svg`,
    })
  ]
});

Setup the library in your Angular application using NgModules:

app.module.ts

// ...
import { provideFastSVG } from '@push-based/ngx-fast-svg';

@NgModule({
  declarations: [AppComponent],
  providers: [
    provideFastSVG({
      url: (name: string) => `path/to/svg-assets/${name}.svg`,
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

or if you're using an older version of the library, you can still do:

// ...
import { FastSvgModule } from '@push-based/ngx-fast-svg';

@NgModule({
  declarations: [AppComponent],
  imports: [
    FastSvgModule.forRoot({
      url: (name: string) => `path/to/svg-assets/${name}.svg`,
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Usage in the template

<fast-svg [name]="svgName" [size]="svgSize"></fast-svg>
<!-- OR -->
<fast-svg [name]="svgName" [width]="svgWidth" [height]="svgHeight"></fast-svg>

Advanced usage

Providing additional options

During setup phase you can provide additional optional settings such as:

  defaultSize?: string;
  suspenseSvgString?: string;
  svgLoadStrategy?: Type<SvgLoadStrategy>;

svgLoadStrategy can be any injectable class that has config that excepts method that accepts url and returns observable string, and load which accepts the configured url as an observable and returns the svg as an observable string.

@Injectable()
export abstract class SvgLoadStrategy {
  abstract load(url: string): Observable<string>;
}

app.module.ts

// ...
import { FastSvgModule } from '@push-based/ngx-fast-svg';
import { loaderSvg } from './assets';
import { HttpClientFetchStrategy } from './fetch-strategy';

@NgModule({
  declarations: [AppComponent],
  imports: [
    FastSvgModule.forRoot({
      url: (name: string) => `path/to/svg-assets/${name}.svg`,
      defaultSize: '32',
      suspenseSvgString: loaderSvg,
      svgLoadStrategy: HttpClientFetchStrategy
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

or in a standalone application:

main.ts

import { provideFastSVG } from '@push-based/ngx-fast-svg';
import { loaderSvg } from './assets';
import { HttpClientFetchStrategy } from './fetch-strategy';

bootstrapApplication(AppComponent, {
  providers: [
    // ... other providers
    provideFastSVG({
      url: (name: string) => `path/to/svg-assets/${name}.svg`,
      defaultSize: '32',
      suspenseSvgString: loaderSvg,
      svgLoadStrategy: HttpClientFetchStrategy
    })
  ]
});

SSR Usage

You can provide your own SSR loading strategy that can look like this:

@Injectable()
export class SvgLoadStrategySsr implements SvgLoadStrategy {
  load(url: string): Observable<string> {
    const iconPath = join(process.cwd(), 'dist', 'app-name', 'browser', url);
    const iconSVG = readFileSync(iconPath, 'utf8');
    return of(iconSVG);
  }
}

And then just provide it in you server module.

app.server.module.ts

@NgModule({
  declarations: [],
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
  ],
  providers: [
    provideFastSVG({
      svgLoadStrategy: SvgLoadStrategySsr,
      url: (name: string) => `assets/svg-icons/${name}.svg`,
    }),
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

Providing a lazy configuration

If you need to provide a lazy configuration you can use the config method in the SvgLoadStrategy:

@Injectable()
class LazyConfigSvgLoadStrategy extends SvgLoadStrategyImpl {
  dummyLazyConfig$ = timer(5_000).pipe(map(() => 'assets/svg-icons'))
  override config(url: string): Observable<string> {
    return this.dummyLazyConfig$.pipe(map((svgConfig) => `${svgConfig}/${url}`));
  }
}

And pass it to the provider function:

import { provideFastSVG } from '@push-based/ngx-fast-svg';

bootstrapApplication(AppComponent, {
  providers: [
    // ... other providers
    provideFastSVG({
      url: (name: string) => `${name}.svg`,
      svgLoadStrategy: LazyConfigSvgLoadStrategy,
    })
  ]
});

Features

:sloth: Lazy loading for SVGs

Lazy loading is referring to loading resources only if they are visible on screen. Like lazy loading imgs. It can be implemented natively over loading attribute or over viewportobserver. This library supports lazy loading for SVGs using purely browser native features.

  • We display an empty SVG at the beginning. Invisible and without dimensions.
  • On View init the size is applied even if no svg is loaded to avoid flickering in dimensions.
  • A suspense svg is displayed at the same time to reduce visual flickering.
  • We use an img element here to leverage the browsers native features:
    • Lazy loading (loading="lazy") to only load the svg that are actually visible
    • The image is styled with display none. this prevents any loading of the resource ever. on component bootstrap we decide what we want to do. When we remove display none it performs the browser native behavior.

:floppy_disk: Caching

We use a DOM caching mechanism to display svg over the 'use' tag and an href attribute. When the browser loaded the svg resource we trigger the caching mechanism.

re-fetch -> cache-hit -> get SVG -> cache in DOM

Cached SVG elements can be reused in multiple places and support different styling.

:rocket: Optimized for performance

This library leverages best performance practices:

  • Component is styled with content-visiblity: auto; and contain: content;. It makes instances outside of viewport completely excluded from browser style recalculation process.
  • Cache is stored in a tag which is not processed by the browser.
  • We use native browser fetch which is not patched by zone.js and is on average 2.5 times faster than fetching over HTTPClient.

🤖 SSR Support

This library also supports SSR. url and loading function can be configured over DI.

🤖 SSR Transfere State (rendered SVG as HTML)

If SSR load svgs on server the rendered HTML ends up in DOM cache and ships to the client. On the client no additional requests are needed.

Comparison

🖥️ Interactive demo available here.

Here's library comparison with other popular SVG solutions.

Library SSR [1] Lazy loading [2] Optimized render performance [3] Transfere State Size
ngx-fast-svg easy browser natively ✔️ ✔️ 1.52 KB
ionic moderate viewport observer ✔️ 1.44 KB
angular-svg-icon moderate 1.54 KB
material easy 16.92 KB
ant moderate 24.38 KB
font-awesome hard 64.75 KB

[1] SSR Server Side Rendering is working. The depending on how easy it is to set it up we distinguish between easy, moderate, hard.

[2] Lazy loading We refer to lazy loading as on demand loading of SVG files based on their visibility in the viewport.

[3] Optimized render performance To display (render) SVGs the browser takes time. We can reduce that time by adding a couple of improvements.


made with ❤ by push-based.io

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory