YouTube Data Source Instead of Direct Embed

We have a number of YouTube videos we are embedding throughout our site and we are getting pinged on GTMetrix & Pingdom for being slow partly due to multiple instances of the YouTube Scripts being loaded.

For instance, our home page has 8 video clips and YouTube is loading 8 versions of the player files and 8 versions of the embed script pushing our page size up quite a bit…

I have had success deferring the script by using the snippets in the link below on other themes but am unable to get the videos to play at all in the X theme. That however, may be due to the fact that we are hiding relative videos and video details and I am also not 100% sure the script is in the correct place – just before the closing body tag.

https://varvy.com/pagespeed/defer-videos.html

Is there are way (preferably not with a new plugin) that can help defer this script so it only loads one instance for all of the vids?

Hello There,

Thanks for writing in!

You can insert the JS script needed to defer your script by adding this code in your child theme’s functions.php file

function add_defer_script(){ ?>
  <script>
    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;
  </script>
<?php } 
add_action('wp_footer', 'add_defer_script');

This code is the correct way of adding the JS code before the closing body tag.

Please let us know how it goes.

1 Like

That went great!

We are delighted to assist you with this.

Cheers!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.