This snippet solves three major problems with background videos on websites:
Apple's Hard Limitations:Includes a special hack (double layer video + div background-image) that makes the video autoplay on iPhone and Safari.
LazyLoad:Videos don't load all at once when the page opens. The script usesIntersectionObserverand starts loading the video only when the user scrolls past200px.
Adaptability:Allows you to set different videos for PCs (horizontal) and phones (vertical), saving traffic.
Basic CSS
This code is responsible for the correct positioning of the layers. Thevideotag is at the very bottom (z-index: -4), and the hack-div is on top of it (z-index: -3).
css
.lazy-video-bg {
position: absolute; /* Or relative if the block should stretch the content */
top: 0; left: 0;
width: 100%; height: 100%;
overflow: hidden;
z-index: -1;
background-color: #000;/* Placeholder color before video loads */
}
/* Layer 1: The video itself (bottom) */
.lazy-video-bg .full-bg-video {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
object-fit: cover;
z-index: -4;
}
/* Layer 2: Safari Hack (on top of video) */
.lazy-video-bg .bg-video-hack {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
z-index: -3;
pointer-events: none;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-color: transparent;
}
HTML code (how to use)
Paste this HTML code where the video should be. The script will automatically find everything using thelazy-video-bgclass.
Option A:Same video for PC and Mobile
If the video is universal, fill in only the_deskattributes. The script will automatically insert them for mobile devices.