1. Stimulus 컨트롤러 및 HTML 준비
data-controller="youtube"로iframe을 감싸고,iframesrc에enablejsapi=1추가.data-youtube-target="player"로iframe지정. 컨트롤러는player타겟과playing(재생 상태),percentageVisible(가시성 임계값) 값을 정의.
2. YouTube API 로딩 및 플레이어 초기화
connect()시#setup()으로 YouTube API 초기화. 중복 로드를 방지하며, 필요시 스크립트 로드 및onYouTubeIframeAPIReady콜백 설정.#createPlayer()는YT.Player인스턴스 생성 및 이벤트 핸들러 등록.onReady시IntersectionObserver설정.onStateChange시 사용자의 수동 일시정지 처리.
3. 뷰포트 기반 비디오 재생 제어 로직
#detectViewport()는IntersectionObserver를 생성하여 요소 가시성 모니터링 (percentageVisibleValue기반 임계값).#adjustPlayback(entry)는 가시성 변경 시 호출:- 뷰포트 밖에 있으면
#pauseWhenOutOfView()로 비디오 일시정지 및playingValue를true로 설정. - 뷰포트 안에 다시 들어오고 이전에 재생 중이었다면 (
playingValue가true),#attemptToPlay()로 비디오 재생 및playingValue를false로 재설정. YouTubeplayVideo()는 Promise를 반환하지 않음.
- 뷰포트 밖에 있으면