I have a video element being used as the background of a section towards the bottom of a page I'm building. I'm trying to build a sort of 'lazy-load' for it by storing the src as a data-src attribute and using jQuery to apply it to the src attribute after the other assets have loaded (since it's not a hero image or anything, I want to load a poster to save cut load-time and then load the video later). It doesn't seem to be working for me at all. The src attribute is applied correctly but the video doesn't load or autoplay. Am I approaching this from the wrong angle? Is there a better way to accomplish it?
Building on wordpress.
Basic HTML
<video width="100%" loop controls autoplay class="connect-bg">
<source data-src="<?php echo get_template_directory_uri(); ?>/contact_Footer.mp4" type="video/mp4">
</video>
jQuery Function
$(window).load(function(){
footer_lazyloader();
});
function footer_lazyloader() {
var $ = jQuery;
$("video.connect-bg source").each(function(){
var sourceFile = $(this).attr('data-src');
$(this).attr('src',sourceFile);
});
}
Lazy loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It's a way to shorten the length of the critical rendering path, which translates into reduced page load times.
For playing the videos on web browsers, there is a new type of video element designed that is HTML5. If you see the message “HTML5 video not found” while playing a video on a web page, it means your browser doesn't support the HTML5 format codecs or missed some video codecs.
The load() method is used to update the audio/video element after changing the source or other settings.
Sometimes we may need to lazy load a video on the webpage — we would like the video to start downloading only when user clicks on the play button. This pre-loading of the video can be prevented using the preload attribute of the <video> element. Setting preload="none" will ensure that video is not preloaded.
You can manually trigger the video to load and play by using '.load()' and '.play()' respectively. Target the parent of the 'source' element using 'parentElement' to accomplish this:
$(function() {
$("video.connect-bg source").each(function() {
var sourceFile = $(this).attr("data-src");
$(this).attr("src", sourceFile);
var video = this.parentElement;
video.load();
video.play();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With