DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Load external libraries dynamically in Angular

To be able to load external libraries it is good to have a service which is responsible to load those scripts!

It will be looks like this

@Injectable({providedIn: 'root'})
export class ExternalLibrariesService {
  static injectLib(src: string): void {
    const script = document.createElement('script');
    script.src = src;
    document.body.appendChild(script);
  }
}
Enter fullscreen mode Exit fullscreen mode

With that service we can easily add external libraries as much as we want!

Example usage

@Component({
  selector: 'app-root',
  template: ``,
})
export class AppComponent implements OnInit {
  private externalLibs = [
    'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',
    'https://code.jquery.com/jquery-3.6.0.slim.min.js'
  ];
  ngOnInit(): void {
    this.externalLibs.forEach(libSrc => ExternalLibrariesService.injectLib(libSrc));
  }
}
Enter fullscreen mode Exit fullscreen mode

Ability to add other important attributes

When we want to use libraries like bootstrap and jQuery CDN, on their site we can see they are using this attributes integrity and crossorigin on the script tag. Let's add these two to our method like this

static injectLib(src: string, integrity?: string, crossOrigin?: string): void {
    const script: HTMLScriptElement = document.createElement('script');
    script.src = src;
    if (integrity) {
      script.integrity = integrity;
    }
    if (crossOrigin) {
      script.crossOrigin = crossOrigin;
    }
    document.body.appendChild(script);
  }
Enter fullscreen mode Exit fullscreen mode

And now let's introduce interface for external libraries in the app, like this

interface IExternalLib {
  src: string;
  integrity?: string;
  crossOrigin?: string;
}
Enter fullscreen mode Exit fullscreen mode

Now we can update our usage example like this

@Component({
  selector: 'app-root',
  template: ``,
})
export class AppComponent implements OnInit {
  private externalLibs: IExternalLib[] = [
    {
      src: 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',
      integrity: 'sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo',
      crossOrigin: 'anonymous'
    },
    {
      src: 'https://code.jquery.com/jquery-3.6.0.slim.min.js',
      integrity: 'sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=',
      crossOrigin: 'anonymous'
    }
  ];
  ngOnInit(): void {
    this.externalLibs.forEach(lib => ExternalLibrariesService.injectLib(lib.src, lib.integrity, lib.crossOrigin));
  }
}
Enter fullscreen mode Exit fullscreen mode

Thank for reading, hope you like it 🙏🏽

Oldest comments (0)