How to load script file dynamically in app.compone

2019-08-27 17:15发布

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.

2条回答
姐就是有狂的资本
2楼-- · 2019-08-27 17:43

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.

查看更多
三岁会撩人
3楼-- · 2019-08-27 17:50

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

查看更多
登录 后发表回答