Using iframe to Embed Youtube Videos
In , Google introduced a new HTML format for embedding youtube videos.
Old Code using “object” Tag
This is their older format using the “object” tag:
<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/h7XjOK_DSmo?fs=1&hl=en_US&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/h7XjOK_DSmo?fs=1&hl=en_US&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>
The following is modified code so the result is valid HTML:
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/h7XjOK_DSmo" width="480" height="385"><param name="movie" value="http://www.youtube.com/v/h7XjOK_DSmo"></object>
New Code Using “iframe”
The following is the new iframe format they are offering:
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/h7XjOK_DSmo?rel=0"></iframe>
Here's how the new code looks in browser:
The new format using iframe is much better, because, according to Google's youtube blog at Source:
If you use the new embed code style, your viewers will be able to view your embedded video in one of our Flash or HTML5 players, depending on their viewing environment and preferences. …
An additional benefit of the new embed style is that it will eventually allow embeds to work on mobile devices, which typically use a built-in player instead of Flash or HTML5.
The iframe is also better because:
- The actual video HTML code is fetched when user loads the page, so you don't have to worry about keeping up-to-date of all your hardcoded embedded video codes on your site, in case any youtube format changes in the future or youtube embed feature changes. When HTML5 comes alone, nothing you need to change on your site.
- You don't have to worry about browser compatibility of your embeded video code now. Google takes care of that.
- The iframe tag is shorter and simpler.
- If you are a HTML validity worrywart like me, with iframe you have less to worry about. Technically, there's no
type="text/html"attribute for “iframe” tag, so Google's new HTML is still incorrect, but it's far better than the extremely complex “embed” tag, or manually crafting and maintaining the not-widely-supported “object” tag.
Why did youtube put a type attribute in iframe for embedded video? See: Source stackoverflow.com
Google has removed the
See: Google and Amazon Generates Invalid HTML.
Ask me question on patreon