在Angular 2中动态加载外部js脚本 [英] Load external js script dynamically in Angular 2

查看:233
本文介绍了在Angular 2中动态加载外部js脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模块可以将外部库与其他逻辑组合在一起,而不会将< script> 标签直接添加到index.html中:

  import'http://external.com/path/file.js'
// import'../js/file.js '

@Component({
selector:'my-app',
template:`
< script src =http://iknow.com/ this / does / not / work / any / file.js>< / script>
< div>模板< / div>`
})
export class MyAppComponent {。 ..}

我注意到 import by ES6规范是静态的,并且在TypeScript transpiled期间而不是在运行时解析。



无论如何使其可配置,因此file.js将从CDN或本地文件夹加载?
如何判断Angular 2是否动态加载脚本?

解决方案

如果您使用的是system.js,可以在运行时使用 System.import()

  export class MyAppComponent然后(refToLoadedModule => {
refToLoadedModule.someFunction();
} {

);
}

如果您使用的是webpack,您可以充分利用其强大的代码通过 require.ensure 分解支持:

  export class MyAppComponent {
constructor(){
require.ensure(['path / to / your / module'],require => {
let yourModule = require('path / to / your / module');
yourModule.someFunction();
});
}
}


I have this module which componentize the external library together with additional logic without adding the <script> tag directly into the index.html:

import 'http://external.com/path/file.js'
//import '../js/file.js'

@Component({
    selector: 'my-app',
    template: `
        <script src="http://iknow.com/this/does/not/work/either/file.js"></script>
        <div>Template</div>`
})
export class MyAppComponent {...}

I notice the import by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.

Anyway to make it configurable so the file.js will be loading either from CDN or local folder? How to tell Angular 2 to load a script dynamically?

解决方案

If you're using system.js, you can use System.import() at runtime:

export class MyAppComponent {
  constructor(){
    System.import('path/to/your/module').then(refToLoadedModule => {
      refToLoadedModule.someFunction();
    }
  );
}

If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure :

export class MyAppComponent {
  constructor() {
     require.ensure(['path/to/your/module'], require => {
        let yourModule = require('path/to/your/module');
        yourModule.someFunction();
     }); 
  }
}

这篇关于在Angular 2中动态加载外部js脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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