Load All Assets Before Video Background When Viewing On Mobile

 Hi guys, I have recently discovered this amazing basic script that will totally help you improve your Mobile Page Speed especially when checking it on Google Page Insight, let's say your homepage has a video background then this script will help you do that.

window.addEventListener('load', function () {

    if (window.innerWidth <= 768) {

      var video = document.querySelector('video');

      var source = document.querySelector('source');

      source.src = 'yourvideofilenamehere.mp4'; // Set the video source

      video.load(); // Load the video

    }

  });

So the window.innerWidth <= 768 code simply tells the browser that when a user views that less than or equal to 768 then it should fire the event listener that whenever all assets are loaded the video will start to play.

Just replace the video source with your actual video and you are good to go.

      var video = document.querySelector('video');
      var source = document.querySelector('source');

The code above simply selects the video tag in the DOM, as well as the code source.

 If you have an HTML code like this below:

<div class="video-container">
<video controls autoplay muted>
<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<img class="fallback-image" src="fallback-image.jpg" alt="Fallback Image">
</div>

The image fallback is useful to improve also your user experience since the video might shown empty while loading the assets so its better to display image first so that when the video starts loading it will display first and then the actual video, if you are familiar with Elementor page builder for WordPress then this features is already available on that plugin.

Post a Comment

Previous Post Next Post