Preloading a youtube embed

14,977

I had the same question and came across this question. After some research, I think I found a cleaner, albeit similar, answer.

When the JavaScript API calls OnYouTubePlayerReady, you press play and add an event listener to onStateChange that will be called every time the player changes from buffering to play.

For example, inside the function you listen for state 3, which is buffering, and as soon as it's called, you pause the video.

You can see this technique in action in this jsFiddle.

Side note: I refrained from using a JavaScript framework in my example, but you could easily put one into place here.

Also, I was unable to abstract the script tag out of the body of the HTML using jsFiddle, but an external script.js file works just fine on my own server.

Share:
14,977
zakdances
Author by

zakdances

Updated on June 04, 2022

Comments

  • zakdances
    zakdances almost 2 years

    I want to have an embedded chromeless youtube video preload its video WITHOUT playing when the page loads. Right now I'm using an awkward "play then quickly pause" script which causes small problems (half-second audio leaks and fails quite a bit). For this seemingly simple functionality, is there a better/more elegant way to preload?

  • zakdances
    zakdances over 12 years
    Doesn't work. From the official docs: "cueVideoByID: Loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until playVideo() or seekTo() is called." In other words, it doesn't actually start buffering the clip.
  • zachzurn
    zachzurn over 12 years
    You are right. It seems like the only way would be to do it the way you are doing it. I can suggest trying to listen for the event "playerStateChanged" and seeing if the state is playing (1) then call pause. You might be able to pause it sooner.
  • trcarden
    trcarden over 11 years
    I found that state 3 wasn't always part of the loading sequence on my high speed connection. Instead what worked was listening to the play state, muting the audio, and pausing.
  • Nathan Wailes
    Nathan Wailes over 6 years
    I could be missing something, but from having read the article, this code doesn't preload a YouTube video without playing it, and thus is not an answer to the question as stated.
  • Nathan Wailes
    Nathan Wailes over 6 years
    As of 2017.11.12, when I try to run the JSFiddle in Chrome I see You need Flash Player version 8 or higher to view this content.