Tal Humy
Tal Humy

Reputation: 1227

Angular 5 - Loading Script After View Is Loaded

I have a legacy script that I need to include in my angular application. The thing about this script is that it relates to a specific component, and it has to be loaded only after the view of the component is loaded. As for today, I succeeded to include it on OnInit function but sometimes (not always for some reason) the CLI throws an error about it.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-player-page',
  templateUrl: './player-page.component.html',
  styleUrls: ['./player-page.component.scss']
})
export class PlayerPageComponent implements OnInit {
  public itemId: string;
  
  constructor() {}

  ngOnInit() {
    //We loading the player srcript on after view is loaded
    require('assets/scripts/player/player.js');
  }

}

The script assumes that elements in the UI exists and it searches them by the id. When adding it on top of the page, it doesn't work. What is the best way to achieve the desired behavior?

Upvotes: 2

Views: 14559

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

There are multiple solutions to this issue.

  1. declare the require const on top of your component

    declare const require: any;
    
    import { Component, OnInit } from '@angular/core';
    
    @Component({})
    ...
    
  2. use the dynamic import() function from typescript

    ngAfterViewInit() {
      //We loading the player script on after view is loaded
      import('assets/scripts/player/player.js');
    }
    
  3. change the library to only start running after you call a function from the component, this way you can add it to the scripts array of your angular.json

Upvotes: 4

Related Questions