Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay loading of html5 video after the rest of the page finished loading

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);
    });
}
like image 851
Jon Hendershot Avatar asked Dec 02 '15 00:12

Jon Hendershot


People also ask

What is video lazy loading?

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.

Why video is not playing in HTML5?

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.

How do you refresh a video tag in HTML?

The load() method is used to update the audio/video element after changing the source or other settings.

How can I make my background video lazy?

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.


1 Answers

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();
  });
});
like image 119
guest271314 Avatar answered Oct 28 '22 13:10

guest271314