Announcement

Collapse
No announcement yet.

Youtube videos and page speed and cookies

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Youtube videos and page speed and cookies

    I've been doing some messing around with pagespeeds, one of the issues that popped up was with the embedding of Youtube videos, they were applying a cookie and the javascript was loading, to fix the cookie is easy, rather than the url being:

    Code:
    https://www.youtube.com/embed/YOURVIDEO
    add -nocookie, so you have:

    Code:
    https://www.youtube-nocookie.com/embed/YOURVIDEO
    With the loading of javascript when the page is loading, you need to change the url src of the video so instead of:

    Code:
    <iframe src="https://www.youtube-nocookie.com/embed/...
    You do:

    Code:
    <iframe src="" data-src="https://www.youtube-nocookie.com/embed/...
    leaving src="" empty and use data-src="" as your video. In the fragment layout or any layout where you embed the video add the following javascript:

    Code:
    <script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
    const iframes = document.querySelectorAll('iframe[data-src]');
    
    if ("IntersectionObserver" in window) {
    const iframeObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
    if (entry.isIntersecting) {
    const iframe = entry.target;
    iframe.src = iframe.getAttribute('data-src');
    observer.unobserve(iframe);
    }
    });
    });
    
    iframes.forEach(iframe => iframeObserver.observe(iframe));
    } else {
    // Fallback for browsers without IntersectionObserver
    iframes.forEach(iframe => {
    iframe.src = iframe.getAttribute('data-src');
    });
    }
    });
    </script>
    This then only loads the iframe video after the page has finished.

    As always backup first.

    EDIT* You can also wrap the javascript in a BlockIf so it's only on page if a video is present.
    Many Thanks
    Lee
    www.mdnsupplies.co.uk
    www.hookandloopfasteners.co.uk
Working...
X