[Fixed] How to load external scripts dynamically in Angular?


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'

    selector: 'my-app',
    template: `
        <script src="http://iknow.com/this/does/not/work/either/file.js"></script>
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 {
    System.import('path/to/your/module').then(refToLoadedModule => {

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

Leave a Reply

(*) Required, Your email will not be published