The YouTube html5 player is loaded with the webpage when embedded using the script from youtube.com. Google also generously store 37 cookies on your computer - before the user clicks play. Not ideal for page speed nor privacy.
Here is a way to show only the poster-image and title on page load and then load the YouTube player in 'Privacy Enhanced' mode when a visitor clicks play.
This improves page speed, and limits the amount of tracking that YouTube and Google can do outside YouTube.com. Here's a music video by Foals:
The code
Here is the CSS and Javascript in a Gist. JS and stylesheet by Amit Agarwal labnol.org with some enhancements.
- Poster image fetched from ytimg.com
- Title retrieved from a oembed json-response from YouTube
- Player loaded on click from youtube-nocookie.com
Play-button in overlay
We need a play-button on top of the poster image, here is the PNG and Photoshop files. It is loaded from the style sheet....
background:url('../images/yt-play5-sq.png') no-repeat;
Load the script in the page HEAD section
Save the javascript from the Gist above as light-yt.js
on your host and load it in HEAD, or use this link from jsdelivr.net
https://cdn.jsdelivr.net/gh/mheland/yt-light@main/yt-light.js
With Ghost CMS we can use Handlebars asset-tag to point to the theme's assets/js folder.
<script type="text/javascript" src="{{asset "js/light-yt.js"}}"></script>
This script adds an event listener document.addEventListener('DOMContentLoaded', initYouTubeVideos);
Add the CSS classes
We also need some styling with the CSS classes from the Gist. .videotitle
scales using the ingenious clamp font-size: clamp(0.9rem, 2vw, 1.3rem)
for scaling. Here's a calculator for clamp() parameters.
<link rel="stylesheet" type="text/css" href="yt-light.css">
Or load the classes from jsdelivr.net..
https://cdn.jsdelivr.net/gh/mheland/yt-light@main/yt-light.css
Embed the video using YouTube ID
Find the YouTube video ID in the URL on youtube.com
Enter the ID as data-id
in this <div>
where you want to embed the video on your page. That's it - only the poster image and title will be loaded, the YouTube player IFRAME is loaded when the user clicks Play.
<div class="youtube-player" data-id="sXiRZhDEo8A"></div>
Here's the result, tested with a movie trailer...
A note on privacy and cookies
This script loads the YouTube player from youtube-nocookie.com
domain which prevents YouTube from setting a persistent cookie. It does, however, store a yt-remote-device-id
identifier in Local Storage on your browser. This ID is (possibly...) anonymous but will track videos you view. Technically this device-ID could be matched against authenticated sessions and Google would be able to identify the user.
The YouTube player will also send the full URL of the page where the video is embedded to Google. To avoid all tracking use a paid service such as Bunny, Streamable, or Vimeo.