Search code examples
htmlperformanceyoutube-apipagespeed

Embedding youtube video


I embed youtube video in my website like this:

<iframe width="320" height="180" src="http://www.youtube.com/embed/12345678"
    style="border: none" allowfullscreen id="myVideo"></iframe>

This iframe's href downloads a this which is 2.7 KB

That download these:

So even though the user didn't watch video yet, he downloads nearly 356 KB data. What would be a better way to show Youtube video in my website but load these data when user wants to watch video ?


Solution

  • You can use the thumbnails and only load the player when the user clicks the thumbnail

    You can see an example of how to do this using AngularJS on the Topic Explorer example

    App:

    https://yt-topic-explorer.googlecode.com/git/dist/index.html

    View:

    https://code.google.com/p/yt-topic-explorer/source/browse/app/views/main.html

    Code snippet:

    <div class="player-container">
            <img ng-click="videoClicked($event.target, videoResult.id)" ng-src="{{videoResult.thumbnailUrl}}" class="thumbnail-image">
            <div class="title"><a ng-href="{{videoResult.href}}" target="_blank">{{videoResult.title}}</a></div>
    </div>
    

    Controller:

    https://code.google.com/p/yt-topic-explorer/source/browse/app/scripts/controllers/main.js

    Code snippet:

    function playVideo(container, videoId) {
        var width = container.offsetWidth;
        var height = container.offsetHeight;
    
        new YT.Player(container, {
          videoId: videoId,
          width: width,
          height: height,
          playerVars: {
            autoplay: 1,
            controls: 2,
            modestbranding: 1,
            rel: 0,
            showInfo: 0
          }
        });