在 Angular 个模块中延迟加载 JS
Lazy Loading JS In Angular Modules
我懒得在 Angular 6 应用程序中加载我的一些功能模块。其中一些功能模块依赖于 JS 库,其他模块不使用这些库,还有一些在延迟加载模块之间共享。
目前,我将这些库包含在 scripts
数组的 angular.json 配置中,但这意味着所有这些库都与应用程序的其余部分一起预先加载,即使它们仅由延迟加载的模块使用。
有没有办法用延迟加载的模块来延迟加载JS库?
我不想在组件中延迟加载它(参见 ),因为这意味着在模块中跨组件复制导入,我想知道这是否可以跨模块完成。
我们遇到了同样的情况,从我们的测试来看,如果模块是懒加载的,你可以简单地只在懒加载模块中导入外部JS文件,然后访问这个JS库就会加载这个模块,下面是我们导入 anychart.js 库的测试示例。
/// <reference path="../../../node_modules/anychart/dist/index.d.ts"/>
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// third-party js lib
import '../../../node_modules/anychart/dist/js/anychart-base.min.js';
import { OrdersRoutingModule } from './orders-routing.module';
import { OrderListComponent } from './order-list/order-list.component';
@NgModule({
imports: [CommonModule, OrdersRoutingModule],
declarations: [OrderListComponent]
})
export class OrdersModule {}
在 app.component.ts 文件中添加以下代码,并在 ngOnInit() 方法中加载外部 js 库。
ngOnInit() {
this.loadScript('../assets/js/custom.js');
}
public loadScript(url: string) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}
我懒得在 Angular 6 应用程序中加载我的一些功能模块。其中一些功能模块依赖于 JS 库,其他模块不使用这些库,还有一些在延迟加载模块之间共享。
目前,我将这些库包含在 scripts
数组的 angular.json 配置中,但这意味着所有这些库都与应用程序的其余部分一起预先加载,即使它们仅由延迟加载的模块使用。
有没有办法用延迟加载的模块来延迟加载JS库?
我不想在组件中延迟加载它(参见
我们遇到了同样的情况,从我们的测试来看,如果模块是懒加载的,你可以简单地只在懒加载模块中导入外部JS文件,然后访问这个JS库就会加载这个模块,下面是我们导入 anychart.js 库的测试示例。
/// <reference path="../../../node_modules/anychart/dist/index.d.ts"/>
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// third-party js lib
import '../../../node_modules/anychart/dist/js/anychart-base.min.js';
import { OrdersRoutingModule } from './orders-routing.module';
import { OrderListComponent } from './order-list/order-list.component';
@NgModule({
imports: [CommonModule, OrdersRoutingModule],
declarations: [OrderListComponent]
})
export class OrdersModule {}
在 app.component.ts 文件中添加以下代码,并在 ngOnInit() 方法中加载外部 js 库。
ngOnInit() {
this.loadScript('../assets/js/custom.js');
}
public loadScript(url: string) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}