YouTube embed videos
Below you'll find three different methods of disabling YouTube embedded videos until the user has consented to analytical cookies.
Method 1: YouTube's privacy enhanced mode
YouTube provides privacy enhanced mode for embedded videos to avoid loading any tracking cookies. This can be configured when you get the embed like from YouTube. This way you don’t have to worry about consents:
<iframe src="https://www.youtube-nocookie.com/embed/NHEaYbDWyQE" frameborder="0" width="560" height="315" allowfullscreen></iframe>
If you don’t have access to the YouTube embed code, you can also replace the url by adding the following javascript to the <head> of your site:
<script type="text/javascript"> var frames = document.getElementsByTagName('iframe'); for (var i=0; i < frames.length; i++) { frames[i].src = frames[i].src.replace(/www.youtube.com/gi,'www.youtube-nocookie.com'); } </script>
Method 2: Delaying loading of the iframe tag
You can use the data-consent attributes for iframes just like for script tags. In addition to inserting the data-consent attribute, you'll also have to change the src attribute to data-src. Here's an example of a YouTube video that won't be loaded unless the user has consented:
<iframe data-consent="analytics" data-src="https://www.youtube.com/embed/NHEaYbDWyQE" frameborder="0" width="560" height="315" allowfullscreen></iframe>
Method 3: Delaying loading of the initialization javascript
Another way would be to load YouTube embed video using inline javascript code which will honor the cookie preferences:
<div id="ytplayer">You must enable analytical cookies to watch this video</div> <script type="text/plain" data-consent="analytics"> // Load the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = "https://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // Replace the 'ytplayer' element with an <iframe> and // YouTube player after the API code downloads. var player; function onYouTubePlayerAPIReady() { player = new YT.Player('ytplayer', { height: '390', width: '640', videoId: 'NHEaYbDWyQE' }); } </script>