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?
I have a good way to dynamically load scripts! Now I use ng6, echarts4 (>700Kb ) ,ngx-echarts3 in my project. when I use them by ngx-echarts's docs, I need import echarts in angular.json : "scripts":["./node_modules/echarts/dist/echarts.min.js"] thus in the login module, page while loading scripts.js, this is big file! I don't want it.
So, I think angular loads each module as a file, I can insert a router resolver to preload js, then begin the module loading!
// PreloadScriptResolver.service.js
Then in the submodule-routing.module.ts ,import this PreloadScriptResolver:
This code works well, and its promises that: After js file loaded, then module begin load! this Resolver can use in many routers
This might work. This Code dynamically appends the
<script>
tag to thehead
of the html file on button clicked.a sample can be
script-loader.service.ts file
and usage
first inject
then
or
If you're using system.js, you can use
System.import()
at runtime:If you're using webpack, you can take full advantage of its robust code splitting support with
require.ensure
:Yet another option would be to utilize
scriptjs
package for that matter whichExample
Install the package:
and type definitions for
scriptjs
:Then import
$script.get()
method:and finally load script resource, in our case Google Maps library:
Demo
You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project.
script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically
script.service.ts is an injectable service that will handle the loading of script, copy
script.service.ts
as it isInject this
ScriptService
wherever you need it and load js libs like this