在组件级别加载JS脚本(不在启动时加载) [英] Load JS script on component level (not at startup)
问题描述
我的项目中有很多JS文件.我想在应用程序启动时加载特定模块或组件时加载它们.
I have lots of JS files in my project. I want to load them when particular module or component load not when the app start.
该怎么做?
当前,我正在将它们加载到index.html
中.另一种方法是将它们添加到angular-cli.json
中.但是两种方式都会在启动时加载JS文件.但是,当特定页面或模块运行时,我需要它们加载.
Currently, I am loading them in index.html
. The other way is to add them in angular-cli.json
. But both ways will load the JS files at the startup. However, I need them to to load when the particular page or module runs.
推荐答案
只需编写一个普通的脚本加载器:
Just write a normal script loader :
public loadScript() {
let body = <HTMLDivElement> document.body;
let script = document.createElement('script');
script.innerHTML = '';
script.src = 'url';
script.async = true;
script.defer = true;
body.appendChild(script);
}
然后在任何需要的地方调用它:
and then call it where ever you want :
export class MyComponent{
ngOnInit(){
this.loadScript();
}
}
但是,如果这些文件是Typescript文件,则也可以通过多种方式延迟加载它们:
But if those files are Typescript files, you can lazy load them as well in a numerous ways:
1-使用默认模块级别的延迟加载
1- Using the default module level lazy loading
2-使用webpack的require
2- Using webpack's require
3-使用SystemJs模块加载器
3- Using SystemJs module loader
这篇关于在组件级别加载JS脚本(不在启动时加载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!