I have a web page with a series of videos embedded on the page:
<video controls preload="metadata" poster="/path/to/video1/poster-image-1.jpg">
<video controls preload="metadata" poster="/path/to/video2/poster-image-2.jpg">
<video controls preload="metadata" poster="/path/to/video3/poster-image-3.jpg">
After I added the videos, the page load slowed down quite a lot, so I set about trying to ascertain the bottleneck.
The Network tab on Firefox Developer Tools reveals that each of the poster
images is returning 206 Partial Content and the poster
images are always being downloaded from the server, never from the local browser cache - and it's this that is slowing down the page by 2-3 seconds.
How can I ensure that the <video>
poster
images are retrieved from the local browser cache instead?
Is the only solution to have a series of invisible images elsewhere on the page, like this:
.preload {width: 1px; height: 1px; opacity: 0;}
<img class="preload" src="/path/to/video1/poster-image-1.jpg" alt="" />
<img class="preload" src="/path/to/video2/poster-image-2.jpg" alt="" />
<img class="preload" src="/path/to/video3/poster-image-3.jpg" alt="" />
I couldn't find a way to cache the poster
attribute images, so I tried removing all the poster
attributes.
I then discovered that even in the absence of poster
, the preload="metadata"
attribute was still significantly slowing down the page load time.
So, ultimately, I replaced preload="metadata"
with preload="none"
and wrote a short script to add the poster
attributes into the DOM asynchronously, several seconds after the page had finished loading:
function asyncVideo() {
var videos = document.getElementsByTagName('video');
for (var i = 0; i < videos.length; i++) {
var posterSrc = videos[i].getElementsByTagName('source')[0].getAttribute('src');
posterSrc = posterSrc.replace('.mp4', '.jpg');
videos[i].poster = posterSrc;
}
}
setTimeout(asyncVideo, 6000);