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.

This data highlights the key performance metrics of these two methods:
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.604s 0.509s 2468 2.604s 12 631 KB 2.818s 13 632 KB 0.549s 0.711s 700 0.549s 2 60 KB 0.709s 3 61 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.