2

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?

Kraken
  • 1,905
  • 12
  • 22
  • This question on the CLI repo should help you. https://github.com/angular/angular-cli/issues/4288 –  Mar 27 '18 at 14:29

1 Answers1

1

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.

joh04667
  • 7,159
  • 27
  • 34