2

Initially I kept below code statically in Index.html and it works.

<script src="/le.min.js"></script>
<script>
    LE.init({
        token: 'token',
        region: 'x'
    });
</script>

due to my requirement I decided to load dynamically for that I wrote sample code.

//loads librabry
jsScript = document.createElement('script');
jsScript.src = `/le.min.js`;
document.head[0].appendChild(jsScript);

//loads initialise function in the script
script = document.createElement('script');
script.innerHtml= `LE.init({
                    token: '${TOKEN}',
                    region: 'US'
                   });`
document.head[0].appendChild(script);

both are appending rightly but it throwing error LE is not defined.If I append the initialise func script as type=text no error but no initialise would happen. How can I achieve this ?

k11k2
  • 2,036
  • 2
  • 22
  • 36

1 Answers1

5

The right way to load a script dynamically in Angular is to use the Renderer2 class. First inject it in your constructor, then use it to add your script to document's head tag.

constructor(private renderer: Renderer2) { }

ngOnInit() {
  const script = this.renderer.createElement('script');
  script.src = `https://cdnjs.cloudflare.com/ajax/libs/le_js/0.0.3/le.min.js`;
  this.renderer.appendChild(document.head, script);
}

The right way to execute functions from a js script file loaded to your app is to declare (declare var LE: any;) this object in your component/service/or any other place you would want to use it. This way you can execute it's function directly instead of using a dynamic script.

Once it is declared you can use it directly, see this example code:

declare var LE: any;

initLE() {
  LE.init({
    token: '${TOKEN}',
    region: 'US'
  });
}

log() {
  LE.log("Hello, logger!");
}

Check out this StackBlitz DEMO

You can see that in this DEMO I'm reaching to LE code, but obviously it is not working because of the missing token.

Full example Code:

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

declare var LE: any;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private renderer: Renderer2) {

  }

  ngOnInit() {
    const script = this.renderer.createElement('script');
    script.src = `https://cdnjs.cloudflare.com/ajax/libs/le_js/0.0.3/le.min.js`;
    this.renderer.appendChild(document.head, script);
  }

  initLE() {
    LE.init({
      token: '${TOKEN}',
      region: 'US'
    });
  }

  log() {
    LE.log("Hello, logger!");
  }
}
benshabatnoam
  • 7,161
  • 1
  • 31
  • 52