如何在 app.component.ts(angular) 中动态加载脚本文件? [英] How to load script file dynamically in app.component.ts(angular)?

查看:44
本文介绍了如何在 app.component.ts(angular) 中动态加载脚本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular2 与打字稿.

I am working in angular2 vs typescript.

在我的 app.component.ts 文件中,我必须根据当前导航器语言按需加载脚本文件.所以我添加了我的功能如下(home.component.ts),

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.

推荐答案

为了加载脚本,它应该可供加载.除非您愿意手动将脚本文件复制到公共文件夹,否则使用 document.createElement 手动添加脚本是错误的做法.

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 已经处理了动态导入.这需要一些额外的措施来确保延迟加载的脚本会被 Webpack 捆绑.导入名称要适合静态分析,可以提供附加选项通过评论.

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.

这篇关于如何在 app.component.ts(angular) 中动态加载脚本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆