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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.