I wonder what the best practices might be for embedding YouTube videos.
I want to embed them without cookies, not influencing negatively the Lighthouse speed, showing up with preview image as long as the full embed is not loaded yet and still offer the same user experience for the interaction.
With this in mind I came up with this blocks/video.yml blueprint:
name: field.blocks.video.name
icon: video
preview: video
fields:
url:
label: field.blocks.video.url.label
type: url
placeholder: field.blocks.video.url.placeholder
caption:
label: field.blocks.video.caption
type: writer
inline: true
dntlink:
type: info
label: Youtube without cookies
text: |
**(link: https://www.youtube-nocookie.com/embed/ text: YouTube DNT target: _blank)**
**(link: http://www.get-youtube-thumbnail.com/ text: YouTube Video Thumbnail target:_blank)**
Here you then copy & paste the original YouTube link, replace manually the first part with the provided youtube-nocookie.com domain and create a thumbnail via the second link which you can upload.
To increase the loading speed I have modified the snippets/blocks/video.php like this:
<?php if ($block->url()->isNotEmpty()): ?>
<figure>
<span class="video" style="--w:16;--h:9;">
<iframe data-src="<?= $block->url() ?>" src="" frameborder="0" allowfullscreen preload="none" loading="lazy"></iframe>
</span>
<?php if ($block->caption()->isNotEmpty()): ?>
<figcaption class="video-caption"><?= $block->caption() ?></figcaption>
<?php endif ?>
</figure>
<?php endif ?>
And added this JavaScript snippet to convert the URL:
// YouTube Defer
if (document.getElementsByTagName('iframe').length > 0){
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
function parseJSAtOnload() {
var element = document.createElement("script");
element.src = "https://www.youtube-nocookie.com/s/player/d82ca80e/player_ias.vflset/de_DE/base.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", parseJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", parseJSAtOnload);
else window.onload = parseJSAtOnload;
}
This works and fulfills most of my mentioned requirements but it doesn’t work anymore with other video platforms (e.g. Vimeo) and feels really clunky.
That’s why I would like to know how others have implemented it.