Search

Stop Video Outside the Viewport on WordPress Sites

In one of the projects I worked on, a considerable number of videos (video) were required on specific pages. Some of those videos needed to span the entire width of the screen, while others, smaller ones, were placed in a specific container.

During my work on the site, I noticed that my laptop (which I don’t underestimate its capabilities) was struggling. The fans started spinning rapidly, the computer heated up, and everything began to respond very slowly.

A quick check in the Task Manager showed that a specific chrome tab, which contains number of videos, was consuming about 50% of the CPU resources.

Resource Consumption without Video Paused Outside Viewport

Initially, I thought there might be some issue with one of the JavaScript files I wrote, but it turned out not to be the case. Videos or HTML5 Videos consume a significant amount of resources from the processor, especially when displayed in full screen.

I am, of course, talking about videos embedded using the HTML5 <video> tag, not YouTube videos or similar.

When you think about it, it’s not correct or efficient because such a video will play when it is outside the Viewport, i.e., outside the area where the user is currently viewing at the given moment. It would be right to stop playing all the videos unless they are within the current user’s viewport for the sake of optimization and better frontend performance.

The isInViewPort.js Library

Searching for a solution led me to the lightweight jQuery library (or plugin) that can tell us whether a specific element is currently in the Viewport, called isInViewport.js.

The basic usage of this plugin is as follows:

$( 'selector:in-viewport' )

When used as a selector, it returns all the elements on the page that match, and from here, additional jQuery methods can be chained. You can also use the is method of jQuery:

$('div:in-viewport').css('background-color', 'red');

// IS THE SAME AS:

var $div = $('div');
if ($div.is(':in-viewport')) {
    $div.css('background-color', 'red');
}

In this code, two operations will set a red background for all elements of type div found in the viewport. Without going into further details, it is worth mentioning that the pseudo-selector we are using (in-viewport) can have two parameters:

$( 'selector:in-viewport( tolerance[, viewport selector] )' )
  • Tolerance – Determines the behavior precision or sensitivity of the action. It represents the distance in pixels beyond the viewport (defined by default or in the second parameter) to which the plugin still considers it part of the viewport.
  • Viewport – You can set any element appearing in the DOM as the viewport. In this case, if you do so, the plugin will refer to this element as the viewport and not the default, which is the window.

Using isInViewPort.js to Pause Video in WordPress

As you can see, using the isInViewPort.js library allows you to interact with any element, whether it is within the viewport of your choice or outside of it. In our case, dealing with a video, let’s see how to use the library to pause it when it’s outside the viewport.

So, download the library and add the isInViewport.js file to your JavaScript folder in your theme (or in the child theme). Then, add the following code to the functions.php file to load this file:

wp_enqueue_script( 'isInViewport', get_bloginfo( 'stylesheet_directory' ) . '/js/isInViewport.js', array( 'jquery' ) );

Please note that we added array( 'jquery' ) as a parameter to the function to ensure that we load the plugin only after jQuery is loaded; otherwise, we will get an error.

Now, add the following code wherever you add JavaScript on your WordPress site to initialize the plugin:

jQuery(document).ready(function ($) {
    "use strict";
    
    /* pause videos if scrolled out of viewport */
    $(window).scroll(function() {
        $('video').each(function(){
            if ($(this).is(":in-viewport( 400 )")) {
                $(this)[0].play();
            } else {
                $(this)[0].pause();
            }
        });
    });
});

In line 7, as you can see in in-viewport, we used a tolerance of -400 to pause the video when it is 400 pixels outside the default viewport (window). You can, of course, play with the parameter until the result matches your preferences, and with that, we’re done.

At this point, every video (HTML5 Video) on the site will stop playing the moment it is outside the viewport, and the use of CPU resources will significantly decrease. See the CPU resource usage after using the plugin – a decrease of about 50 percent:

Resource Usage After Pausing Video Outside Viewport

Summary

This is, in essence, a solution for embedded HTML5 videos on the site using the <video> tag. In a similar vein to this post, if the videos on your site are YouTube or Vimeo videos, you can improve page loading time with a bit of JavaScript.

Take a look at this post on deferring JavaScript for YouTube videos if you’re interested in the topic. In any case, feel free to comment on the post as always… 🙂

Roee Yossef
Roee Yossef

I develop websites & custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Quick Navigation

Up!
Blog