Home > Mobile >  How to await loading external script in Angular?
How to await loading external script in Angular?

Time:01-31

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

CodePudding user response:

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.

  • Related