对于视频媒体比较多的页面比如产品详情,需要用到大量的视频素材展示产品,不能一进入网页就全部将视频请求,这会占用大量的网络带宽,影响加载性能。推荐做法,进入视口再请求视频,支持仅加载、仅播放一次。
Web组件代码:
javascript
class VideoIntersectionInsert extends HTMLElement {
constructor() {
super();
this._observer = null;
this._isPlaying = false;
this._loaded = false;
this._playedOnce = false;
this._onlyLoad = false;
}
connectedCallback() {
const videoHtml = this.dataset.src;
if (!videoHtml) return;
this._observer = new IntersectionObserver(
(entries) => {
const entry = entries[0];
const visibleHeight = entry.intersectionRect.height;
this._onlyLoad = this.hasAttribute("onlyLoad");
if (this.hasAttribute("once") && this._playedOnce ) return;
if (visibleHeight >= 100 && !this._loaded) {
const videoDiv = document.createElement("div");
videoDiv.innerHTML = videoHtml;
this._video = videoDiv.querySelector("video");
this.querySelectorAll("img").forEach((b) => (b.style.visibility = "hidden"));
this.appendChild(this._video);
this._loaded = true;
if(this._onlyLoad) return
this._video.play().catch(() => {});
this._isPlaying = true;
this._video.addEventListener("ended", () => {
if (this.hasAttribute("once")) {
this._playedOnce = true;
this._observer?.disconnect();
this._video.pause();
}
});
}
if (visibleHeight >= 100 && !this._isPlaying && !this._playedOnce && !this._onlyLoad) {
this._video.play().catch(() => {});
this._isPlaying = true;
} else if (visibleHeight < 100 && this._isPlaying && !this.hasAttribute("once")) {
this._video.pause();
this._isPlaying = false;
}
},
{
root: null,
threshold: Array.from({ length: 101 }, (_, i) => i / 100),
}
);
this._observer.observe(this);
}
disconnectedCallback() {
this._observer?.disconnect();
}
}
if (!customElements.get("video-intersection-insert")) {
customElements.define("video-intersection-insert", VideoIntersectionInsert);
}
用法:
html
//仅进入视口加载 ,后续的播放由自定义代码决定
<div class="video-container">
{% assign video = section.settings.video | video_tag: controls: false, loop: true, muted: true %}
<video-intersection-insert
onlyLoad
data-src="{{ video | escape }}"
>
<img width="auto" height="auto" loading="lazy"
src="{{ section.settings.video.preview_image | image_url }}"
alt="{{ section.settings.video.preview_image.alt }}"
>//视频预览图,可保证网络差的情况下展示空白
</video-intersection-insert>
</div>
//进入视口只播放一次,once可强制取消loop
<div class="video-container">
{% assign video = section.settings.video | video_tag: controls: false, loop: true, muted: true %}
<video-intersection-insert
once
data-src="{{ video | escape }}"
>
<img width="auto" height="auto" loading="lazy"
src="{{ section.settings.video.preview_image | image_url }}"
alt="{{ section.settings.video.preview_image.alt }}"
>
</video-intersection-insert>
</div>