Skip to content

Commit 695b84f

Browse files
crisbetoannieyw
authored andcommitted
docs(youtube-player): update loading example to avoid loading API multiple times (#20767)
Adds some extra logic to the asynchronous loading example that illustrates how to avoid adding the API multiple times. (cherry picked from commit cc310f9)
1 parent 33aa531 commit 695b84f

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/youtube-player/README.md

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,31 +20,33 @@ If your video is found at https://www.youtube.com/watch?v=PRQCAL_RMVo, then your
2020

2121
```typescript
2222
// example-module.ts
23-
import {NgModule} from '@angular/core';
23+
import {NgModule, Component, OnInit} from '@angular/core';
2424
import {YouTubePlayerModule} from '@angular/youtube-player';
2525

2626
@NgModule({
27-
imports: [
28-
YouTubePlayerModule,
29-
],
27+
imports: [YouTubePlayerModule],
3028
declarations: [YoutubePlayerExample],
3129
})
3230
export class YoutubePlayerExampleModule {
3331
}
3432

33+
let apiLoaded = false;
34+
3535
// example-component.ts
3636
@Component({
3737
template: '<youtube-player videoId="PRQCAL_RMVo"></youtube-player>',
3838
selector: 'youtube-player-example',
3939
})
4040
class YoutubePlayerExample implements OnInit {
4141
ngOnInit() {
42-
// This code loads the IFrame Player API code asynchronously, according to the instructions at
43-
// https://developers.google.com/youtube/iframe_api_reference#Getting_Started
44-
const tag = document.createElement('script');
45-
46-
tag.src = "https://www.youtube.com/iframe_api";
47-
document.body.appendChild(tag);
42+
if (!apiLoaded) {
43+
// This code loads the IFrame Player API code asynchronously, according to the instructions at
44+
// https://developers.google.com/youtube/iframe_api_reference#Getting_Started
45+
const tag = document.createElement('script');
46+
tag.src = 'https://www.youtube.com/iframe_api';
47+
document.body.appendChild(tag);
48+
apiLoaded = true;
49+
}
4850
}
4951
}
5052

0 commit comments

Comments
 (0)