Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
Tal Humy Avatar asked Aug 26 '26 17:08

Tal Humy


1 Answers

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

like image 196
Poul Kruijt Avatar answered Aug 28 '26 08:08

Poul Kruijt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!