Prevent Background Videos From Pre-Loading On Mobile
Prevent Background Videos From Pre-Loading On Mobile
Nov 26, 2018
Prevent Background Videos From Pre-Loading On Mobile
This post was originally created on our sister site WP Cover. View Original Article November 26, 2018
Background looping videos have become very popular over the last couple years. They look fantastic, are very engaging, and a nice way to differentiate your company or business from competitors.
The downside to the looping videos is they can be fairly large video files and they don’t work on mobile devices. Most developers understand this and will simply hide the video using CSS on mobile and display an image instead. However, many don’t know that in some cases the background video may still be pre-loading on mobile devices even though it is hidden. How do you prevent this from happening?
Fortunately, we can fix this issue with some jQuery and simple HTML changes. Here’s how we’re going to do it:
First, update your video src from:
TO:
Next, add some additional jQuery that will check if the video is visible. If so, it will swap the data-src element to the src element:
jQuery(
function() {
var bgv = jQuery('#bgvid');
if (bgv.is(':visible')) {
jQuery('source', bgv).each(
function() {
var el = jQuery(this);
el.attr('src', el.data('src'));
}
);
bgv[0].load();
}
}
)
That’s all there is to it! Give it a go and let us know how it worked for you in the comments.