Search code examples
javascriptjqueryyoutubeyoutube-iframe-api

Lazy Load youtube video from iframe API


I want to lazy load the youtube video with iframe API. ie. load only the poster image in the beginning and when user clicks on it then only load the actual image and its content.


Solution

  • Finally it worked, below code is in angularJS.

    HTML

    <div data-ng-repeat="video in videoIds track by $index">
        <div id="uniQueId" ng-click="playVideo(video, 'player' + $index)">
            <div class="video-play-button"></div>
        </div>
    </div>
    

    JS

     $scope.playVideo = function(videoId, id) {
            $scope.players[id] = new YT.Player(id, {
                videoId: videoId,
                width: '400',
                height: '300',
                playerVars: { 'autoplay': 1 },
                events: {
                    'onStateChange': $scope.onPlayerStateChange
                }
            });
        };