How to Add Script Dynamically in Angular Application

Pankaj Kumar
2 min readJul 27, 2021

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

/**
* 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.

Thanks!

This article was originally posted over JsonWorld

Click here to Join live Classed led by IT Professionals of Tech Giants like TCS, IBM, Accenture, Infosys, etc.

--

--

Pankaj Kumar

JavaScript Developer | Blogger — Expert in NodeJS, Firebase, Angular, React(Instructor at edhint.com)