我正在制作一个视频 slider ,其中下一个视频在前一个视频结束之前开始 - 循环播放。同时我需要更新每个进度条。下面的代码可以工作,但是 Chrome 正在烧毁我的 MacBook。我做错了什么吗?我怎样才能提高性能?有免费幻灯片,视频没有loop="true"属性。我只是通过播放第一个视频来启动 slider 。
videos.on('timeupdate', function () {
var progress = this.currentTime / this.duration * 100 + '%';
$(this).closest('.slide').find('.js-video-progress').width(progress);
if ((this.currentTime * 1000 + 1000) > this.duration * 1000) {
if ($(this).closest('.slide').next('.slide').length) {
$(this).closest('.slide').next('.slide').addClass('is-swiped').find('video')[0].play();
} else {
$('.slide').eq(0).addClass('is-swiped').find('video')[0].play();
}
}
});
最佳答案
timeupdate
可能会以很高的速率触发(甚至可能比屏幕刷新率更快),因此无论您在那里做什么,都必须尽可能轻。
每次你调用 jQuery 的方法时,它们都会做很多事情,并且总是返回新对象,这很快就会污染你的所有内存,迫使 GarbageCollector 每次都进来。因此,不要调用同一函数两次,而是将结果存储在变量中。
这是一种稍微更好的方法,将每个重用对象存储在处理程序本身中:
videos.on('timeupdate', function () {
var time = this.currentTime, // it's a getter function, store
var dur = this.duration;
var progress = time / duration * 100 + '%';
var $this = $(this); // store
var $slide = $this.closest('.slide');
var $progress = $slide.find('.js-video-progress');
var $slide_next;
$progress.width(progress);
if ((time * 1000 + 1000) > dur * 1000) {
$slide_next = $slide.next('.slide');
if ($slide_next.length) {
$slide_next
.addClass('is-swiped')
.find('video')[0]
.play();
} else {
$slide.eq(0)
.addClass('is-swiped')
.find('video')[0]
.play();
}
}
});
但就我个人而言,我认为甚至会更深入,冒着冗长的风险,并将所有需要的对象存储在我只需在处理程序中查找的静态对象中:
videos.each(function attach_data() {
var $this = $(this);
var $slide = $this.closest('.slide');
var $progress = $slide.find('.js-video-progress');
var $video = $slide.eq(0).find('video');
var $slide_next = $slide.next('.slide');
var $next_video = $slide_next.find('video');
$this.data('$tree', {
slide: $slide.eq(0),
progress: $progress,
video: $video,
slide_next: $slide_next,
video_next: $video_next
})
})
.on('timeupdate', function () {
var time = this.currentTime;
var dur = this.duration;
var progress = time / duration * 100 + '%';
// retrieve our stored object
var $tree = $(this).data('$tree');
$tree.progress.width(progress);
if ((time * 1000 + 1000) > dur * 1000) {
if ($tree.slide_next.length) {
$tree.slide_next.addClass('is-swiped');
$tree.next_video[0].play(); // you may want to add a check the <video> really exists
} else {
$tree.slide.addClass('is-swiped');
$tree.video[0].play();
}
}
});
关于javascript - 视频循环性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397130/