Block YouTube Cookies when lazyloading Thumbnail

Viewed 581

On https://bm-translations.de/ I have an YouTube-iframe embedded with the nocookie domain of YouTube. For speed optimization I am only loading an thumbnail via lazyload. This is my code:

//youtube lazyload thumbnail
    ( function() {

    var youtube = document.querySelectorAll( ".youtube" );
    
    for (var i = 0; i < youtube.length; i++) {
        
        var source = "https://img.youtube-nocookie.com/vi/"+ youtube[i].dataset.embed +"/sddefault.jpg";
        
        var image = new Image();
                image.src = source;
                image.addEventListener( "load", function() {
                    youtube[ i ].appendChild( image );
                }( i ) );
        
                youtube[i].addEventListener( "click", function() {

                    var iframe = document.createElement( "iframe" );

                            iframe.setAttribute( "frameborder", "0" );
                            iframe.setAttribute( "allowfullscreen", "" );
                            iframe.setAttribute( "src", "https://www.youtube-nocookie.com/embed/"+ this.dataset.embed +"?rel=0&iv_load_policy=3&autoplay=1" );

                            this.innerHTML = "";
                            this.appendChild( iframe );
                } );    
    };
    
} )();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
<iframe name="frame" style="display:none;"></iframe>

Unfortunately its setting a bunch of cookies: enter image description here

As I know it from the WordPress Borlabs-Cookie Plugin, it is possible to use YouTube iframes without setting cookies as you can see here for example (scroll to the end of the page): https://keimster.de/ueber-das-keimen/ enter image description here

I wondered if anyone knows how to adjust the code or any other good solution to make it gdpr ready without having a cookie-banner (I have no technical option to save the consents etc. and give the user the option to optout)?

1 Answers

If you look closely, you have two img tags:

enter image description here

You have duplicate codes:

  • The code in your globaljs.js loads from youtube.com.

enter image description here

  • The code inside your script tag embed in home loads from www.youtube-nocookie.com

enter image description here

Last Step:

For thumbnails img.youtube-nocookie.com does not work. You were fetching thumbnail from youtube.com all along. Change your thumbnail loading code to:

var source = "https://i1.ytimg.com/vi/"+ youtube[i].dataset.embed +"/sddefault.jpg";
Related