marksfrancis
marksfrancis

Reputation: 1742

Lazy Loading JS In Angular Modules

I'm lazy loading some of my feature modules in an Angular 6 application. Some of those feature modules have dependencies on JS libraries, which no other modules use, and some which are shared between lazy loaded modules.

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).

Is there a way to lazy load JS libraries with the lazy loaded modules? 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.

Upvotes: 2

Views: 5451

Answers (2)

Shirantha Madusanka
Shirantha Madusanka

Reputation: 1695

Add the following code in app.component.ts file and load your external js libraries in ngOnInit() method.

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

Upvotes: 0

Leon
Leon

Reputation: 354

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.


/// <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 {}

Upvotes: 4

Related Questions