简体   繁体   English

在 Angular 模块中延迟加载 JS

[英]Lazy Loading JS In Angular Modules

I'm lazy loading some of my feature modules in an Angular 6 application.我懒惰地在 Angular 6 应用程序中加载我的一些功能模块。 Some of those feature modules have dependencies on JS libraries, which no other modules use, and some which are shared between lazy loaded modules.其中一些功能模块依赖于其他模块不使用的 JS 库,还有一些在延迟加载的模块之间共享。

At the moment, I'm including those libraries in the angular.json configuration in the scripts array, but that means that all those libraries are eager-loaded with the rest of the application, even though they are only used by the lazy loaded module(s).目前,我将这些库包含在scripts数组的 angular.json 配置中,但这意味着所有这些库都与应用程序的其余部分一起预先加载,即使它们仅被延迟加载模块使用(s)。

Is there a way to lazy load JS libraries with the lazy loaded modules?有没有办法用延迟加载的模块延迟加载 JS 库? I'd rather not lazy load it within a component (see How to load external scripts dynamically in Angular? ) as this would mean copying the import across components within the module, I'm wondering if this can be done across a module.我宁愿不在组件中延迟加载它(请参阅如何在 Angular 中动态加载外部脚本? ),因为这意味着在模块内跨组件复制导入,我想知道这是否可以跨模块完成。

We are having the same situation, from our test, if the module is lazy-loading, you can simply just only import the external JS file in the lazy-loading module, then this JS library will load when accessing this module, below is our test example which import anychart.js library.我们遇到了同样的情况,从我们的测试来看,如果模块是延迟加载的,你可以简单地只在延迟加载模块中导入外部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 {}

Add the following code in app.component.ts file and load your external js libraries in ngOnInit() method.在 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); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM