How to Add Script Dynamically in Angular Application

    Feb 09, 2021       by Pankaj Kumar

While working with an Angular application, You often need to add script tags dynamically in the application. Now adding a script tag in the app applies differently for an SSR(Server Side Rendering) application and a normal application that render on the browser. Let's see all the approach below:

Angular application without SSR

 

 
private loadScript() {
let chatScript = document.createElement("script");
chatScript.type = "text/javascript";
chatScript.async = true;
chatScript.src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js";
document.body.appendChild(chatScript);
 
}
 

 

Angular application with SSR

 

While working with SSR app, We can't access DOM in the normal way because the application renders on the server so You can not write the exact same code written above. Angular provides a few inbuild libraries to handle this. Implementation can be done usinng two approaches one is to directly implement into the Component and the other is to create a service to use this at multiple places. We will see both ways below:

Implementation inside Component

 

 
import { Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
 
class Home implements OnInit {
 
constructor(
  private _renderer2: Renderer2,
  @Inject(DOCUMENT) private _document: Document
) { }
 
public ngOnInit() {
 
  let script = this._renderer2.createElement('script');
  script.type = `application/ld+json`;
  script.text = `
  {
    "@context": "https://schema.org"
    /* Enter other needed data here */
  }
`;
 
  this._renderer2.appendChild(this._document.body, script);
}
}
 

 

Implementation using Service

 

 
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
 
/**
* Service to automate creation of JSON-LD Microdata.
*/
class scriptService {
 
constructor(
  @Inject(DOCUMENT) private _document: Document
) { }
 
/**
* Set JSON-LD Microdata on the Document Body.
*
* @param renderer2 The Angular Renderer
* @param data The data for the JSON-LD script
* @returns Void
*/
public setJsonLd(renderer2: Renderer2, data: any): void {
 
  let script = renderer2.createElement('script');
  script.type = 'application/ld+json';
  script.text = `${JSON.stringify(data)}`;
  renderer2.appendChild(this._document.body, script);
}
}
 

 

Conclusion

Adding script dynamically in Angular application is not very complex task as it seems, For it basic understanding of Angular is needed.

I hope this article helped you to understand How to add script dynamically in angular application. You can also find other demos/articles at Angular Sample Projects here to start working on enterprise-level applications.

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


Find other similar Articles here: