Twitter LogoFacebook Logo
Loading and Using JavaScript in Angular
Learn how to load and use JavaScript code inside your Angular project.
By: King Wai Mark

To load the files, locate the JavaScript files on your computer and place them inside the assets folder of the project. 

Image from Codeible.com

Next, open the angular.json file and locate the scripts property inside. 

Image from Codeible.com

In here, place the path of each JavaScript file you want to load into the array.


You can right click on the file in the explorer pane to get the path of the document and paste each path inside the array. 

Remember to change the backward slashes into forward slashes.

"scripts": [

   "src/assets/ExampleJS1.js"
]

The assets folder is inside the src folder so we do “src/assets/” and the name of our file. 

When we run our app, it will load and execute the code in JavaScript files.

Here is what is inside the ExampleJS1.js file:

function greet(){
   alert("Hello");
}

alert("Pop up");

Result:

Image from Codeible.com

Using Functions in the JS File

To use the functions or variables in the JavaScript files, declare a reference in a TypeScript file by typing declare and then the variable or function you want to reference.

import { Component } from '..'

declare function greet(): void;

@Component({
   ....
})
export class AppCompoent {

}

Then call it in the code.

import { Component } from '..'

declare function greet(): void;

@Component({
   ....
})
export class AppCompoent {

   constructor(){
      greet();
   }

}

Using CDNs

If you have a CDN or a link to an online repository for the JavaScript file, you can just put script tags in the index.html page to load your files. 

<!doctype html>
<html lang="en">
<head>

  <script src="..."></script>  

</head>
<body>
  <app-root></app-root>
</body>
</html>

However, you cannot add script elements in the html page of your components.

To do load JavaScript files in a component, you have to do it manually inside the TypeScript file.


Go into the app component TypeScript file and create a script element object. 

Then set the value of the src property to the path of the JavaScript file you want to load. This can be a URL or a local path in the project. 

Lastly, add the script element to the body of the HTML page. 

import { Component } from '..'

declare function greet(): void;

@Component({
   ....
})
export class AppCompoent {

   myScriptElement: HTMLScriptElement;

   constructor(){
      greet();

      this.myScriptElement = document.createElement("script");
      this.myScriptElement.src = ".....";
      document.body.appendChild(this.myScriptElement);

   }

}


Sign In