Kraken
Kraken

Reputation: 1955

Include script tag conditionally in angular 4 app

I am using Angular 4.4.6 and have <script> tag outside my app-root. it looks like this

<script src="someUrlForQa"></script>

and i want to delete this one and include

<script src="someUrlForProd"></script>

when it will be on production.

What is the right way to do it? Maybe using angular-cli.json somehow?

Upvotes: 2

Views: 832

Answers (1)

joh04667
joh04667

Reputation: 7427

You could do this using plain Javascript.

let el = document.createElement('script');

if(condition) {
   el.src = 'someUrl';
}
else {
   el.src = 'otherUrl';
}

document.head.append(el);

However, it's against the Angular style guide to interact directly with the DOM. If you do this in Angular, the 'Angular way' of creating this would be by injecting and using the Renderer2 service:

constructor(private _renderer: Renderer2) {}

public someMethod() {
    let el = this._renderer.createElement('script');
    el.src = 'conditionalUrl';
    this._renderer.appendChild(el, this_renderer.selectRootElement('body'));
}

As far as when to do this in Angular, you could hijack the APP_INITIALIZER service and provide your own initialization code. Check out this answer for more information.

Upvotes: 1

Related Questions