Igor Simic
5 years ago

Angular Component - Dynamically load external JavaScript


In this example we will load external JavaScript library from Angular component. I will show you two different ways how to include 3rd party JavaScript library within component: simple load, and load with listener when library is finished loaded so we can execute some init functions

1. Load JS on init and do not listen when library is loaded. Inside of component.ts:
public loadExternalScript(url: string) {
  const body = <HTMLDivElement> document.body;
  const script = document.createElement('script');
  script.innerHTML = '';
  script.src = url;
  script.async = true;
  script.defer = true;
  body.appendChild(script);
}

ngOnInit() {
  this.loadExternalScript('https://apis.google.com/js/client:platform.js');
}

2. Load JS library and listen when loading is finished using Angular render method:
...
import {Renderer2} from '@angular/core';

export class MyComponent implements OnInit {

  constructor(
    private renderer: Renderer2
  ) { }

renderExternalScript(src: string): HTMLScriptElement {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.async = true;
  script.defer = true;
  this.renderer.appendChild(document.body, script);
  return script;
}

ngOnInit() {
  
  this.renderExternalScript('https://apis.google.com/js/client:platform.js').onload = () => {
    console.log('Google API Script loaded');
    // do something with this library
  }

}
}