Search code examples
iframebfcache

Is there a way to embed a youtube iframe and still have the bfcache work?


According to the chrome devtools the youtube iframe uses a Media Device Dispatcher which prevents the bfcache to work for that site. Here is how the iframe is set up:

<iframe src="https://www.youtube.com/embed/{id}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; web-share" allowfullscreen />

{id} would be replaced with the video id.


Solution

  • A quick, partial solution, would be to add loading=lazy to the iframe if the YouTube embed is off screen. That way if the user didn't scroll down that far then it wouldn't block bfcache usage.

    On a similar vein, using a you facade to avoid loading the YouTube embed until the user actually looked like they want to watch the video would also allow the bfcache to be used more often: https://developer.chrome.com/docs/lighthouse/performance/third-party-facades/#youtube_embedded_player

    But no there is currently no way to prevent this completely. However, the good news is that the Chrome team are working on these APIs to see if they can prevent them from blocking bfcache usage. The first reason for blocking has already been solved: https://bugs.chromium.org/p/chromium/issues/detail?id=1502395 In Chrome Canary you can see the MediaDeviceDispatcher is now not listed as a reason for blocking. Unfortunately I am sometimes seeing another API the YouTube embed uses instead (EmbedderExtensionMessaging), but not always seeing that so might be partially solved at least in Chrome v122.