Video APIs and mobile devices

When developing websites it’s inevitable that you’ll come across the need to implement videos of some sort, and to save your own server’s bandwidth you’re using a video provider like YouTube or Vimeo.

Now, it’s easy to just drop in the embed code where it’s needed. And there’s nothing wrong with that. However, embed a large amount of videos and you’re likely going to see slow downs in your page loads.

The simplest way to deal with this is to leverage the power of their respective APIs to load videos on demand. And when doing so, it may be useful to have these videos play automatically as soon as they’re loaded too.

While this works fine on desktop computers, I’ve recently found out that this won’t work very well on mobile devices. Trying to dynamically load a video and then using JavaScript to automatically start playing it will result in the video box remaining black and not responding to anything. Removing the auto play part of the script allows the video to load and will allow the user to hit play on it manually.

So why does this happen? Well, as it turns out this is somewhat intentional. In my quest to fix this issue when it occurred during development, I stumbled across this Safari HTML5 Audio and Video Guide. This article blatantly gives the following, and very valid, reason:

Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.

In short: to prevent things from hogging costly data, embedded media won’t play until the user tells it to. While I can’t find any specific documentation for Android, one can only assume that it’s treated the same way for the same reasons.

A good compromise is to verify whether you’re on one of these devices, before calling your play() function on your video.

Disclaimer: I don’t usually condone the use of browser/device sniffing. It’s a bad habit and there’s really no way to guarantee it’s future-proof. However in this case, I’m not sure if there’s an alternative, because checking the window’s width alone is just as wibbly-wobbly.

To do so, all you really need to do is something similar to this(Sorry people on 800×600 screens, if you’re still there!):

if ( !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/) || 
     jQuery(window).width() > 1024 ) {
        // Whatever play function you have
}

And that’s it. It won’t be running any code if the device’s reported user agent contains iPhone, iPod, iPad, Android, or BlackBerry, or if the width of the screen is smaller than 1024px(Decided on this value because of tablets in landscape mode, as I said, width alone is just as wibbly-wobbly and unreliable).