有条理地从index.html以角度2/4添加/删除脚本

时间:2017-10-06 04:57:19

标签: angular

我正在尝试使用angular重写网站,并且有一个页面使用不同的脚本集,因此我无法使用当前的index.html,因为它没有必要加载,因为它没有必要js文件

那么是否可以根据路由有条件地添加/删除脚本?例如,如果我在这条路线上,我想将此脚本文件添加到index.html

1 个答案:

答案 0 :(得分:0)

确定,你当然可以做到这一点。这是一种方法,但您可以将它包含在要运行它的组件中,然后延迟加载到它的路径,以便在访问该路径之前不会加载脚本

 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);
        }
    }