Mike
Mike

Reputation: 103

add / remove script conditionally from index.html in angular 2/4

I'm trying to rewrite a website using angular and there is one page using different set of script so i can't use the current index.html as that one page will failed to load because it doesn't have the necessary js file

So Is it possible to add/remove script conditionally based on the route ? for example if i'm on this route i wanted to add this script file to the index.html

Upvotes: 0

Views: 3294

Answers (1)

FussinHussin
FussinHussin

Reputation: 1814

sure, you can certainly do that. this is one way, but you could really just include it in the component you want to run it in, then lazy load the route to it, so that the script won't load until that route is visited

 import { ActivatedRouteSnapshot } from '@angular/routing';

    constructor(route: ActivatedRoute){}

    ngOnInit() {
        const script = document.createElement('script');
        script.src ='../../assets/js/myScript.js';
        if (this.route === 'root/with/script') {
            document.body.appendChilde(script);
        }
    }

Upvotes: 2

Related Questions