How to load script file dynamically in app.component.ts(angular)?

雨燕双飞 提交于 2019-12-11 17:43:02

问题


I am working in angular2 vs typescript.

In my app.component.ts file i have to load the script files on demand based current navigator language. So i have added my function like below(home.component.ts),

export class HomeComponent {
constructor() {
    this.loadDynmicallyScript();
  } 
public loadDynmicallyScript() {
    let node = document.createElement('script');
    node.src = "../node_modules/xxxxxxxxxx/xx." +   navigator.language"+".min.js";
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
 }

But this not works. But i have to load the files on demand based on current navigator language. How to achive this? Thanks for any help.


回答1:


import * as _script from 'assets/js/index.js';

you can import like this but before importing the scripts change your function to exports then use.

and call the needed functions that needs to be loaded on the pageload in ngOnInit




回答2:


In order for the script to be loaded, it should be available for loading. Unless you're willing to copy script files manually to public folder, adding a script manually with document.createElement is wrong move.

Webpack already handles dynamic imports. This requires some additional measures to make sure that lazy loaded script will be bundled by Webpack. Import name should be suitable for static analysis, additional options can be provided through comments.



来源:https://stackoverflow.com/questions/48973822/how-to-load-script-file-dynamically-in-app-component-tsangular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!