最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to load script and its function dynamically in angular - Stack Overflow

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question asked Jan 23, 2019 at 10:17 k11k2k11k2 2,0442 gold badges23 silver badges37 bronze badges 5
  • The script file probably isnt loaded yet, therefore LE is not defined. You'll need to use the onload event: stackoverflow./questions/16230886/… – Erik Svedin Commented Jan 23, 2019 at 10:21
  • I believe you need an onload event handler for the first script – Jeremy Thille Commented Jan 23, 2019 at 10:21
  • use Angular safe pipe implementation DomSanitizer(bypassSecurityTrustScript) – Omprakash Sharma Commented Jan 23, 2019 at 10:23
  • I hope could be helpful this answer - stackoverflow./questions/41547505/… – Omprakash Sharma Commented Jan 23, 2019 at 10:34
  • I'm calling those in ngAfterViewInit what onload would help me here in angular ? – k11k2 Commented Jan 23, 2019 at 10:41
Add a ment  | 

1 Answer 1

Reset to default 7

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./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 ponent/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.ponent.html',
  styleUrls: ['./app.ponent.scss']
})
export class AppComponent implements OnInit {
  constructor(private renderer: Renderer2) {

  }

  ngOnInit() {
    const script = this.renderer.createElement('script');
    script.src = `https://cdnjs.cloudflare./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!");
  }
}
发布评论

评论列表(0)

  1. 暂无评论