Categories
Angular Answers

How to dynamically load external JavaScript file from Angular component?

Spread the love

Sometimes, we want to dynamically load external JavaScript file from Angular component.

In this article, we’ll look at how to dynamically load external JavaScript file from Angular component.

How to dynamically load external JavaScript file from Angular component?

To dynamically load external JavaScript file from Angular component, we can create script tags dynamically and attach it to the body.

For instance, we write

//...
export class AppComponent implements OnInit {
  ngOnInit() {
    this.loadScript("http://www.some-library.com/library.js");
    this.loadScript("../assets/js/my-library.js");
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement>document.body;
    const script = document.createElement("script");
    script.innerHTML = "";
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

to add the loadScript method that creates the script element with document.createElement.

Then we set a few attributes of the script element with

script.innerHTML = "";
script.src = url;
script.async = false;
script.defer = true;

Then we call body.appendChild with script to attach the script element into the body element.

Conclusion

To dynamically load external JavaScript file from Angular component, we can create script tags dynamically and attach it to the body.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *