HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptangularMajorCanonical

How to load external scripts dynamically in Angular?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
externalangularhowloaddynamicallyscripts

Problem

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

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

@Component({
    selector: 'my-app',
    template: `
        
        Template`
})
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?

Solution

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();
     }); 
  }
}

Code Snippets

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

Context

Stack Overflow Q#34489916, score: 73

Revisions (0)

No revisions yet.