Suave.js/Echo.js Hybrid for Lazy Loading Video
HTML
<ul>
<li>
<a>
<video muted loop autoplay data-echo="http://ak0.picdn.net/shutterstock/videos/975718/preview/stock-footage-man-at-home-listening-to-music-on-the-ground-in-the-living-room.{mp4, webm}" width="200" height="268"></video>
</a>
</li>
<li>
<a>
<video muted loop autoplay data-echo="http://ak8.picdn.net/shutterstock/videos/899926/preview/stock-footage-christmas-greeting-card-with-shining-christmas-tree-and-small-house-on-background.{mp4, webm}" width="200" height="268"></video>
</a>
</li>
<li>
<a>
<video muted loop autoplay data-echo="http://ak8.picdn.net/shutterstock/videos/3371102/preview/stock-footage-light-bulb-on-black-background.{mp4, webm}" width="200" height="268"></video>
</a>
</li>
<li>
<a>
<video muted loop autoplay data-echo="http://ak.picdn.net/shutterstock/videos/1722979/preview/stock-footage-colorful-and-dynamic-nebula-great-space-background-seamless-loop.{mp4}" width="200" height="268"></video>
</a>
</li>
<li>
<a>
<video muted loop autoplay data-echo="http://ak4.picdn.net/shutterstock/videos/646507/preview/stock-footage-abstract-green-tunnel-background.{mp4, webm}" width="200" height="268"></video>
</a>
</li>
</ul>
JavaScript
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);
Echo.init({
offset: 200,
throttle: 50
});