Js doee
Js doee

Reputation: 333

how can I dynamically add a cdn link to ionic app

i am building a mobile app with ionic, i want to add a cdn link to a page only wen i am in that page, that is in test.page.html and not in index.html, but its not working, please how can i add a cdn link to a page and remove it when i am no longer in that page

here's my code

<ion-content>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>

<div id="map"></div>
......
</ion-content>

Upvotes: 0

Views: 584

Answers (1)

Sergey Rudenko
Sergey Rudenko

Reputation: 9227

You can do that by addting:

ngAfterViewInit() {

  let script = document.createElement('script');
  script.onload = () => {
    // perform actions you need on load of the script
  }
  script.src = "https://cdn.script.url";
  script.onerror = () => {
      // handle errors
  };
  document.body.appendChild(script);
  
};

to your test.page.ts

This is not great as you leverage directly document object inside angular, but may suffice your use case.

To avoid accessing document this way you can:

import { DOCUMENT } from '@angular/common';
...

constructor(
    @Inject(DOCUMENT) private document: Document,
    ...
  ) {
}

Then refer to document as this.document since we injected it as dependency for that test page class.

Upvotes: 0

Related Questions