How to Load External JS Scripts Dynamically in AngularJS ? - GeeksforGeeks

27 Feb, 2020
The task is to load a JS code either from a CDN or JS file stored in the system dynamically at runtime in AngularJS i.e. JavaScript code should be loaded dynamically. For example, on a button press or on some event.
Whenever we want to load the script file we would have to create an element of type “script” using document.createElement. We would then specify its src attribute to be the location of the script either CDN or a local js file. Once that’s done, we will have to append the tag to an HTML element that’s already existing in the DOM. For example, the head element.
Syntax:
const node = document.createElement('script');
node.src = 'SCRIPT_FILE_OR_URL_HERE'
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);

Example 1: In this example, we are loading a load.js file from file system dynamically on component load.
app.component.html
app.component.ts
load.js
<div style="text-align:center;">    <h1 style="color: green;">        GeeksForGeeks    </h1></div>
import { Component } from '@angular/core';  @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css']})export class AppComponent {   title = 'Load script GFG';   constructor() {     this.loadScripts();   }     // Method to dynamically load JavaScript   loadScripts() {       // This array contains all the files/CDNs     const dynamicScripts = [        'assets/load.js'     ];     for (let i = 0; i < dynamicScripts.length; i++) {       const node = document.createElement('script');       node.src = dynamicScripts[i];       node.type = 'text/javascript';       node.async = false;       document.getElementsByTagName('head')[0].appendChild(node);     }  }}
alert('load js has been loaded'); 
Output: As soon as the app.component loads, the script loads as well and displays the alert window.
Example 2: In this example, we will load the load.js script on button click.
app.component.html
app.component.ts
load.js
<div style="text-align:center;">    <h1 style="color: green;">        GeeksForGeeks    </h1>    <button (click)="loadScripts($event)">        Click me to load JS    </button></div>
import { Component } from '@angular/core';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  title = 'Load script GFG';  constructor() {  }  loadScripts($event) {    const dynamicScripts = [      'assets/load.js'    ];    for (let i = 0; i < dynamicScripts.length; i++) {      const node = document.createElement('script');      node.src = dynamicScripts[i];      node.type = 'text/javascript';      node.async = false;      document.getElementsByTagName('head')[0].appendChild(node);    }  }}
alert('load js has been loaded'); 
Output: As the button is pressed, the JS file loads.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
AngularJS-Misc
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?