如何使用Echo.js延迟加载视频(mp4)?

时间:2013-12-30 14:19:18

标签: javascript video lazy-loading

我很难理解为什么视频(mp4)没有出现。

HTML标记看起来像......

<video muted="" loop="" autoplay="autoplay" poster="" width="380" height="718" >
    <source  data-echo="path/video.mp4" type="video/mp4"/>
</video>    

在浏览器中,DOM看起来像......

<video muted="" loop="" autoplay="autoplay" poster="" width="380" height="718">
    <source data-echo="path/video.mp4" type="video/mp4" src="path/video.mp4">
</video>

Echo.js似乎按预期工作,但视频不会出现。我错过了什么?

这是一个jsFiddle,其中有一个工作示例。

1 个答案:

答案 0 :(得分:0)

在一点点帮助下,我将echo.js与Suave.js结合起来。 DEMO

window.Echo = (function (window, document, undefined) {

  'use strict';

  var store = [], offset, throttle, poll;

  var _inView = function (el) {
    var coords = el.getBoundingClientRect();
    return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset));
  };

 var _pollImages = function () {
    for (var i = store.length; i--;) {
      var self = store[i];
      var videoHTML = self.parentNode.innerHTML;
      var dataAttr = self.getAttribute('data-echo');
      var videoSource = dataAttr.substr(0, dataAttr.lastIndexOf('.')+ 1);
      var fileExts = dataAttr.substring(dataAttr.indexOf('{')+1,dataAttr.indexOf('}')).replace(/\s/g, '').split(',');
      var sourceVideo = "";
        for (var d = 0; d < fileExts.length; d++) {
          var extension = fileExts[d];
          var sourceSrc = videoSource + extension;
          var sourceType = 'video/' + extension;
          sourceVideo += "<source" + " " + "src=\"" + sourceSrc + "\"" + " " + "type=\"" + sourceType + "\"" + "/>";
        }
      if (_inView(self)) {
        var videoHybrid = videoHTML.replace(/></, '>' + sourceVideo + '<');
        self.parentNode.innerHTML = videoHybrid;
        store.splice(i, 1);
      }
    }
  };

  var _throttle = function () {
    clearTimeout(poll);
    poll = setTimeout(_pollImages, throttle);
  };

  var init = function (obj) {
    var nodes = document.querySelectorAll('[data-echo]');
    var opts = obj || {};
    offset = opts.offset || 0;
    throttle = opts.throttle || 250;

    for (var i = 0; i < nodes.length; i++) {
      store.push(nodes[i]);
    }

    _throttle();

    if (document.addEventListener) {
      window.addEventListener('scroll', _throttle, false);
    } else {
      window.attachEvent('onscroll', _throttle);
    }
  };

  return {
    init: init,
    render: _throttle
  };

})(window, document);