Search code examples
javascriptjqueryhtmlhtml5-videosrc

Disable HTML 5 video from loading


I have a setup where there is a background video displaying depending on the current weather conditions, shown here: http://pitfarmtennis.co.uk/cms/.

There are 6 different videos, currently the jQuery code to decide which to show just sets them to display:none, This sadly means all of them still load.

This is the jQuery that is currently making a certain video play, in this case a sunny video:

    /*Day-sun*/
    if((weather.code == "28")||(weather.code == "30")||(weather.code == "44")) {
        $('.home-bg-sun').css("display","inline");
    }

One solution I have tried is to set all of the src attributes in the HTML to data-src, and then changing the relevant one to src to fire the video, which hasn't worked to date, but I might have done something wrong:

jQuery:

    /*Day-sun*/
    if((weather.code == "28")||(weather.code == "30")||(weather.code == "44")) {
        $('.home-bg-sun').attr('src', $('.home-bg-sun').attr('data-src'));
    }

HTML:

<div class="home-bg-sun">
    <video class="home-bg-sun-video" autoplay loop poster="wp-content/themes/eddiemachado-bones-9db85e4/library/images/home-bg-sun-first_frame.jpg">
        <source id="home-bg-sun-video-source" src="wp-content/themes/eddiemachado-bones-9db85e4/library/videos/home-bg-sun.webm" type="video/webm">
        <source id="home-bg-sun-video-source" src="wp-content/themes/eddiemachado-bones-9db85e4/library/videos/home-bg-sun.mp4" type="video/mp4">
    </video>
</div>

Any help would be much appreciated!

PS: I am using Yahoo Weather to fetch weather conditions.


Solution

  • There is a preload attribute on the video element.
    You may want to try the metadata or none value.

    But note that this attribute is only a hint for browsers, which are not forced to follow it.