Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to await loading external script in Angular?

There is an Angular app with external loaded script that adds a own entry point as functon into global scrope (Window). How to await loading this in Angular app. Now the Angular component can not get access to the window property initialize:

declare global {
  function initialize(id: string): HTMLElement;
}

export class Layer  {
  container: HTMLElement;

  constructor(private state: State) {}

  create() {
    this.container = initialize('div');
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In Angular you can use APP_INITIALIZER to accomplish the above. It allows you to load a script to the window before initializing your application.

Refer the code snippet below :

import { APP_INITIALIZER, NgModule } from '@angular/core';

export function loadScript(document: any) {
  return () => {
    const script = document.createElement('script');
    script.src = 'https://example.com/script.js';
    script.async = true;
    script.onload = () => {
      console.log('External script loaded!');
    };
    document.head.appendChild(script);
  };
}

@NgModule({
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: loadScript,
      deps: [Document],
      multi: true,
    },
  ],
})
export class AppModule {}

In the above sample snippet loadScript function creates a new script element, sets its source to the URL of the external script, multi: true option allows for multiple instances of the APP_INITIALIZER to be provider to the app to be registered.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading