javascript 延迟加载 html5 视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34033115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:09:17  来源:igfitidea点击:

Delay loading of html5 video

javascriptjqueryhtmlhtml5-videolazy-loading

提问by Jon Hendershot

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?

我有一个视频元素用作我正在构建的页面底部的部分的背景。我试图通过将 src 存储为 data-src 属性并在其他资产加载后使用 jQuery 将其应用于 src 属性来为其构建一种“延迟加载”(因为它不是英雄图像或任何东西,我想加载一张海报以节省加载时间,然后稍后加载视频)。它似乎根本不适合我。src 属性已正确应用,但视频无法加载或自动播放。我是从错误的角度接近这个吗?有没有更好的方法来实现它?

Building on wordpress.

建立在wordpress上。

Basic HTML

基本 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

jQuery 函数

$(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);
    });
}

回答by guest271314

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:

您可以分别使用 '.load()' 和 '.play()' 手动触发视频加载和播放。使用“parentElement”定位“source”元素的父元素以完成此操作:

$(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();
  });
});