视频循环性能不佳

问题描述 投票:0回答:1

我正在制作一个视频滑块,其中跟随视频在前一个结束之前开始 - 在一个循环中。同时我需要更新每个进度条。下面的代码有效,但Chrome正在刻录我的macbook。我做错了吗?如何提高性能?有免费幻灯片,视频没有loop =“true”属性。我只是通过播放第一个视频来启动滑块。

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();
        }
    }
});
javascript jquery html html5 video
1个回答
1
投票

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();
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.