Performance comparison of two methods for embedding a YouTube video
The default method for embedding a YouTube video uses an inline iframe. The custom JavaScript method involves creating an iframe element and inserting it into the DOM on the click event of an anchor.
This has a big impact on improving performance as none of the third-party code that YouTube includes is
requested, until the anchor is clicked. Specifically, base.js
which is ~407 KB in size.
In terms of user experience, due to the use of the autoplay=1
parameter, the effect is similar
to (if not the same as) clicking on the play button in the YouTube player iframe. This causes the video to
start playing within the iframe as soon as it has loaded after clicking on the anchor.
Default | JavaScript | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Document Complete | Fully Loaded | Document Complete | Fully Loaded | ||||||||||||||
Load Time | Start Render | Speed Index | Time | Requests | Bytes In | Time | Requests | Bytes In | Load Time | Start Render | Speed Index | Time | Requests | Bytes In | Time | Requests | Bytes In |
2.757s | 0.590s | 2670 | 2.757s | 16 | 658 KB | 2.923s | 17 | 658 KB | 1.221s | 0.741s | 854 | 1.221s | 6 | 93 KB | 1.362s | 7 | 93 KB |
WebPagetest was used to obtain the data. |
The time and bytes in metrics highlight the biggest performance differences between these two methods. Whilst the default method for embedding a YouTube iframe provides the convenience of getting the video ready for the user to play it immediately, it comes at the cost of an increased load time. This also assumes that the user actually wants to watch the video.
Using JavaScript to only load the iframe on click of the anchor, in other words, once the user has shown intent to watch the video, reduces the initial page load time drastically.
Additionally, the JavaScript method makes use of progressive enhancement in that the anchor has a valid
href
so the user can still navigate to the video on YouTube in the event that JavaScript
fails.