diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f3fe393 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-16 Bjørn Klinggaard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 94eb7e8..f6e3bb2 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,13 @@ -hey, be lazy -===== +#hey, be lazy +[![Downloads](https://img.shields.io/npm/dm/blazy.svg?style=flat)](https://www.npmjs.com/package/blazy) +[![Latest Stable Version](https://img.shields.io/npm/v/blazy.svg?style=flat)](https://www.npmjs.com/package/blazy) +[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/dinbror/blazy/blob/master/LICENSE) + bLazy is a lightweight script for lazy loading and multi-serving images, iframes, videos and more (less than 1.4KB minified and gzipped). It’s written in pure JavaScript why it doesn’t depend on 3rd-party libraries such as jQuery. It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data usage if he/she doesn't browse the whole page. **Table of Contents**
1. [Demo](https://github.com/dinbror/blazy#demo)
-2. [Usage & API](https://github.com/dinbror/blazy#how-to--api)
+2. [Usage & API](https://github.com/dinbror/blazy#usage--api)
3. [Why be lazy?](https://github.com/dinbror/blazy#why-be-lazy)
4. [Changelog](https://github.com/dinbror/blazy#changelog)
5. [License](https://github.com/dinbror/blazy#license)
@@ -48,7 +51,41 @@ Exchange `latest` with the specific version number if you want to lock it in. * bLazy supports all browsers used today including legacy browsers like IE7 and 8. * bLazy supports all main module formats like AMD, CommonJS and globals. + +## WISHLIST/NEW FEATURES REQUESTED BY YOU +* Only preload "first frame" of progressive jpegs. +* Add support for CSS background property; [image-set](https://cloudfour.com/examples/image-set/) ([caniuse](http://caniuse.com/#feat=css-image-set)). +* Add a class when the lazyloading begins. +* Option to keen load once on screen images have loaded. +* Add option to disable success/error classes +* Animate the container that contains the image you lazy load. You can do that today by adding/removing a class in the success callback. + ## CHANGELOG +### v 1.8.2 (2016/10/25) ### +* Added null check in public `load` function. +* Bugfix: Fixed `this` issue defaulting to window when passing `revalidate` or `destroy` in setTimeout as reference [#73](https://github.com/dinbror/blazy/issues/73) and [#112](https://github.com/dinbror/blazy/pull/112). Thanks [PeteDuncanson](https://github.com/PeteDuncanson). +* Bugfix: If parts of container is outside window use the viewport boundaries [#113](https://github.com/dinbror/blazy/issues/113) and [#114](https://github.com/dinbror/blazy/pull/114). Thanks [dbirkbeck](https://github.com/dbirkbeck). + +### v 1.8.1 (2016/10/22) ### +* Bugfix: Created polyfill and check for support of `Element.closest` which was introduced in the container fix in v. 1.8.0. + +### v 1.8.0 (2016/10/16) ### +* Bugfix: Non-visible images being loaded inside container [#23](https://github.com/dinbror/blazy/issues/23) and [#96](https://github.com/dinbror/blazy/issues/96). + +### v 1.7.1 (2016/10/14) ### +* Bugfix: In safari the picture element always loaded the default/fallback image [#92](https://github.com/dinbror/blazy/issues/92). + +### v 1.7.0 (2016/10/10) ### +* Bugfix: When lazyloading picture elements it also loaded the fallback/regular image [#92](https://github.com/dinbror/blazy/issues/92) and [108](https://github.com/dinbror/blazy/pull/108). Thanks [@idoshamun](https://github.com/idoshamun) +* Refactored loadElement function to avoid redundancy. + +### v 1.6.4 (2016/10/08) ### +* Bugfix: When lazyloading srcset images it also loaded the fallback/regular image [#99](https://github.com/dinbror/blazy/pull/99). Thanks [@m0uH](https://github.com/m0uH) + +### v 1.6.3 (2016/09/30) ### +* Changed event listener to passive listener [#106](https://github.com/dinbror/blazy/pull/106). Thanks [@idoshamun](https://github.com/idoshamun) +* Added support for web components (shadow dom) [#107](https://github.com/dinbror/blazy/pull/107). Thanks again [@idoshamun](https://github.com/idoshamun) + ### v 1.6.2 (2016/05/09) ### * Fixed bug introduced in v.1.6.0, not using retina/breakpoint src [#90](https://github.com/dinbror/blazy/issues/90). diff --git a/blazy.js b/blazy.js index b09b163..00af78d 100644 --- a/blazy.js +++ b/blazy.js @@ -1,5 +1,5 @@ /*! - hey, [be]Lazy.js - v1.6.2 - 2016.05.09 + hey, [be]Lazy.js - v1.8.2 - 2016.10.25 A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy) (c) Bjoern Klinggaard - @bklinggaard - http://dinbror.dk/blazy */ @@ -21,8 +21,7 @@ 'use strict'; //private vars - var _source, _viewport, _isRetina, _attrSrc = 'src', - _attrSrcset = 'srcset'; + var _source, _viewport, _isRetina, _supportClosest, _attrSrc = 'src', _attrSrcset = 'srcset'; // constructor return function Blazy(options) { @@ -48,18 +47,21 @@ scope.options = options || {}; scope.options.error = scope.options.error || false; scope.options.offset = scope.options.offset || 100; + scope.options.root = scope.options.root || document; scope.options.success = scope.options.success || false; scope.options.selector = scope.options.selector || '.b-lazy'; scope.options.separator = scope.options.separator || '|'; - scope.options.container = scope.options.container ? document.querySelectorAll(scope.options.container) : false; + scope.options.containerClass = scope.options.container; + scope.options.container = scope.options.containerClass ? document.querySelectorAll(scope.options.containerClass) : false; scope.options.errorClass = scope.options.errorClass || 'b-error'; - scope.options.breakpoints = scope.options.breakpoints || false; // obsolete + scope.options.breakpoints = scope.options.breakpoints || false; scope.options.loadInvisible = scope.options.loadInvisible || false; scope.options.successClass = scope.options.successClass || 'b-loaded'; scope.options.validateDelay = scope.options.validateDelay || 25; scope.options.saveViewportOffsetDelay = scope.options.saveViewportOffsetDelay || 50; scope.options.srcset = scope.options.srcset || 'data-srcset'; scope.options.src = _source = scope.options.src || 'data-src'; + _supportClosest = Element.prototype.closest; _isRetina = window.devicePixelRatio > 1; _viewport = {}; _viewport.top = 0 - scope.options.offset; @@ -69,11 +71,11 @@ /* public functions ************************************/ scope.revalidate = function() { - initialize(this); + initialize(scope); }; scope.load = function(elements, force) { var opt = this.options; - if (elements.length === undefined) { + if (elements && elements.length === undefined) { loadElement(elements, force, opt); } else { each(elements, function(element) { @@ -81,11 +83,10 @@ }); } }; - scope.destroy = function() { - var self = this; - var util = self._util; - if (self.options.container) { - each(self.options.container, function(object) { + scope.destroy = function() { + var util = scope._util; + if (scope.options.container) { + each(scope.options.container, function(object) { unbindEvent(object, 'scroll', util.validateT); }); } @@ -127,7 +128,7 @@ function initialize(self) { var util = self._util; // First we create an array of elements to lazy load - util.elements = toArray(self.options.selector); + util.elements = toArray(self.options); util.count = util.elements.length; // Then we bind resize and scroll events if not already binded if (util.destroyed) { @@ -149,7 +150,7 @@ var util = self._util; for (var i = 0; i < util.count; i++) { var element = util.elements[i]; - if (elementInView(element) || hasClass(element, self.options.successClass)) { + if (elementInView(element, self.options) || hasClass(element, self.options.successClass)) { self.load(element); util.elements.splice(i, 1); util.count--; @@ -161,22 +162,55 @@ } } - function elementInView(ele) { + function elementInView(ele, options) { var rect = ele.getBoundingClientRect(); - return ( - // Intersection - rect.right >= _viewport.left && rect.bottom >= _viewport.top && rect.left <= _viewport.right && rect.top <= _viewport.bottom - ); + + if(options.container && _supportClosest){ + // Is element inside a container? + var elementContainer = ele.closest(options.containerClass); + if(elementContainer){ + var containerRect = elementContainer.getBoundingClientRect(); + // Is container in view? + if(inView(containerRect, _viewport)){ + var top = containerRect.top - options.offset; + var right = containerRect.right + options.offset; + var bottom = containerRect.bottom + options.offset; + var left = containerRect.left - options.offset; + var containerRectWithOffset = { + top: top > _viewport.top ? top : _viewport.top, + right: right < _viewport.right ? right : _viewport.right, + bottom: bottom < _viewport.bottom ? bottom : _viewport.bottom, + left: left > _viewport.left ? left : _viewport.left + }; + // Is element in view of container? + return inView(rect, containerRectWithOffset); + } else { + return false; + } + } + } + return inView(rect, _viewport); + } + + function inView(rect, viewport){ + // Intersection + return rect.right >= viewport.left && + rect.bottom >= viewport.top && + rect.left <= viewport.right && + rect.top <= viewport.bottom; } function loadElement(ele, force, options) { // if element is visible, not loaded or forced if (!hasClass(ele, options.successClass) && (force || options.loadInvisible || (ele.offsetWidth > 0 && ele.offsetHeight > 0))) { - var dataSrc = ele.getAttribute(_source) || ele.getAttribute(options.src); // fallback to default 'data-src' + var dataSrc = getAttr(ele, _source) || getAttr(ele, options.src); // fallback to default 'data-src' if (dataSrc) { var dataSrcSplitted = dataSrc.split(options.separator); var src = dataSrcSplitted[_isRetina && dataSrcSplitted.length > 1 ? 1 : 0]; + var srcset = getAttr(ele, options.srcset); var isImage = equal(ele, 'img'); + var parent = ele.parentNode; + var isPicture = parent && equal(parent, 'picture'); // Image or background image if (isImage || ele.src === undefined) { var img = new Image(); @@ -192,14 +226,8 @@ var onLoadHandler = function() { // Is element an image if (isImage) { - setSrc(ele, src); //src - handleSource(ele, _attrSrcset, options.srcset); //srcset - //picture element - var parent = ele.parentNode; - if (parent && equal(parent, 'picture')) { - each(parent.getElementsByTagName('source'), function(source) { - handleSource(source, _attrSrcset, options.srcset); - }); + if(!isPicture) { + handleSources(ele, src, srcset); } // or background-image } else { @@ -209,11 +237,20 @@ unbindEvent(img, 'load', onLoadHandler); unbindEvent(img, 'error', onErrorHandler); }; + + // Picture element + if (isPicture) { + img = ele; // Image tag inside picture element wont get preloaded + each(parent.getElementsByTagName('source'), function(source) { + handleSource(source, _attrSrcset, options.srcset); + }); + } bindEvent(img, 'error', onErrorHandler); bindEvent(img, 'load', onLoadHandler); - setSrc(img, src); //preload - } else { // An item with src like iframe, unity, simpelvideo etc - setSrc(ele, src); + handleSources(img, src, srcset); // Preload + + } else { // An item with src like iframe, unity games, simpel video etc + ele.src = src; itemLoaded(ele, options); } } else { @@ -236,22 +273,38 @@ addClass(ele, options.successClass); if (options.success) options.success(ele); // cleanup markup, remove data source attributes - ele.removeAttribute(options.src); + removeAttr(ele, options.src); + removeAttr(ele, options.srcset); each(options.breakpoints, function(object) { - ele.removeAttribute(object.src); + removeAttr(ele, object.src); }); } - function setSrc(ele, src) { - ele[_attrSrc] = src; - } - function handleSource(ele, attr, dataAttr) { - var dataSrc = ele.getAttribute(dataAttr); + var dataSrc = getAttr(ele, dataAttr); if (dataSrc) { - ele[attr] = dataSrc; - ele.removeAttribute(dataAttr); + setAttr(ele, attr, dataSrc); + removeAttr(ele, dataAttr); + } + } + + function handleSources(ele, src, srcset){ + if(srcset) { + setAttr(ele, _attrSrcset, srcset); //srcset } + ele.src = src; //src + } + + function setAttr(ele, attr, value){ + ele.setAttribute(attr, value); + } + + function getAttr(ele, attr) { + return ele.getAttribute(attr); + } + + function removeAttr(ele, attr){ + ele.removeAttribute(attr); } function equal(ele, str) { @@ -268,9 +321,9 @@ } } - function toArray(selector) { + function toArray(options) { var array = []; - var nodelist = document.querySelectorAll(selector); + var nodelist = (options.root).querySelectorAll(options.selector); for (var i = nodelist.length; i--; array.unshift(nodelist[i])) {} return array; } @@ -284,7 +337,7 @@ if (ele.attachEvent) { ele.attachEvent && ele.attachEvent('on' + type, fn); } else { - ele.addEventListener(type, fn, false); + ele.addEventListener(type, fn, { capture: false, passive: true }); } } @@ -292,7 +345,7 @@ if (ele.detachEvent) { ele.detachEvent && ele.detachEvent('on' + type, fn); } else { - ele.removeEventListener(type, fn, false); + ele.removeEventListener(type, fn, { capture: false, passive: true }); } } @@ -314,4 +367,4 @@ fn.apply(scope, arguments); }; } -}); \ No newline at end of file +}); diff --git a/blazy.min.js b/blazy.min.js index 0d4c8a7..649abfd 100644 --- a/blazy.min.js +++ b/blazy.min.js @@ -1,6 +1,6 @@ /*! - hey, [be]Lazy.js - v1.6.2 - 2016.05.09 + hey, [be]Lazy.js - v1.8.2 - 2016.10.25 A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy) (c) Bjoern Klinggaard - @bklinggaard - http://dinbror.dk/blazy */ - (function(p,m){"function"===typeof define&&define.amd?define(m):"object"===typeof exports?module.exports=m():p.Blazy=m()})(this,function(){function p(b){var c=b._util;c.elements=B(b.options.selector);c.count=c.elements.length;c.destroyed&&(c.destroyed=!1,b.options.container&&k(b.options.container,function(a){n(a,"scroll",c.validateT)}),n(window,"resize",c.save_viewportOffsetT),n(window,"resize",c.validateT),n(window,"scroll",c.validateT));m(b)}function m(b){for(var c=b._util,a=0;a=e.left&&f.bottom>=e.top&&f.left<=e.right&&f.top<=e.bottom||q(d,b.options.successClass))b.load(d),c.elements.splice(a,1),c.count--,a--}0===c.count&&b.destroy()}function x(b,c,a){if(!q(b,a.successClass)&&(c||a.loadInvisible||0=window.screen.width)return r=a.src,!1});setTimeout(function(){p(a)})}}); \ No newline at end of file + (function(q,m){"function"===typeof define&&define.amd?define(m):"object"===typeof exports?module.exports=m():q.Blazy=m()})(this,function(){function q(b){var c=b._util;c.elements=E(b.options);c.count=c.elements.length;c.destroyed&&(c.destroyed=!1,b.options.container&&l(b.options.container,function(a){n(a,"scroll",c.validateT)}),n(window,"resize",c.saveViewportOffsetT),n(window,"resize",c.validateT),n(window,"scroll",c.validateT));m(b)}function m(b){for(var c=b._util,a=0;a=c.left&&b.bottom>=c.top&&b.left<=c.right&&b.top<=c.bottom}function z(b,c,a){if(!t(b,a.successClass)&&(c||a.loadInvisible||0=window.screen.width)return u=a.src,!1});setTimeout(function(){q(a)})}}); \ No newline at end of file diff --git a/bower.json b/bower.json index eab2657..7add708 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "bLazy", "main": "blazy.js", - "version": "1.6.2", + "version": "1.8.2", "description": "A fast lightweight pure JavaScript script for lazy loading and multi-serving images, iframes, videos and more.", "homepage": "https://github.com/dinbror/blazy", "keywords": [ @@ -13,6 +13,8 @@ "responsive", "image", "images", + "picture", + "srcset", "javascript", "performance" ], diff --git a/example/index.html b/example/index.html index e42d1ae..dcce0d7 100644 --- a/example/index.html +++ b/example/index.html @@ -68,19 +68,31 @@ } .container { background-color: #1E1E1E; - overflow-x: scroll; - overflow-y: hidden; height:0; padding-bottom:66%; } - .list{ + .horizontal.container{ + overflow-x: scroll; + overflow-y: hidden; + } + .horizontal .list{ font-size:0; width:300%; } - .list .wrapper { + .horizontal .list .wrapper { display: inline-block; width:33.3%; } + .vertical.container{ + overflow-x: hidden; + overflow-y: scroll; + } + .vertical .list{ + width: 100%; + } + .vertical .list .wrapper{ + width: 100%; + } img { max-width: 100%; } @@ -154,18 +166,18 @@

How to lazyload

Examples

    -
  1. Lazy load images
  2. -
  3. Lazy load background image
  4. -
  5. Horizontal lazy load
  6. -
  7. Lazy load iframe
  8. -
  9. Lazy load HTML5 video
  10. -
  11. Lazy load script file
  12. +
  13. Lazy load images, regular, retina, srcset and picture element
  14. +
  15. Lazy load background image
  16. +
  17. Lazy load inside container (vertical & horizotal)
  18. +
  19. Lazy load iframe
  20. +
  21. Lazy load HTML5 video
  22. +
  23. Lazy load script file
-
+

1.1: Default lazyload image example

Lazy load images example 1a @@ -227,26 +239,26 @@

1.5: Lazy load image example with picture element

+ data-srcset="http://placehold.it/1024x682?text=Min-650" /> + data-srcset="http://placehold.it/600x400?text=Min-465" /> Lazy load image example with picture element + alt="Lazy load image example with picture element" />
     <picture> 
         <source 
              media="(min-width: 650px)"
-             data-srcset="image-650.jpg"> 
+             data-srcset="image-650.jpg" /> 
         <source 
              media="(min-width: 465px)" 
-             data-srcset="image-465.jpg">
+             data-srcset="image-465.jpg" />
         <img class="b-lazy"
-             data-src="default.jpg">
+             data-src="default.jpg" />
     </picture>
 			
@@ -259,7 +271,7 @@

1.6: Lazyload image with retina support example

<img class="b-lazy" data-src="image.jpg|retina-image.jpg" />
-
+

2: Lazy load background image example

@@ -268,9 +280,9 @@

2: Lazy load background image example

<div class="b-lazy" data-src="image.jpg"></div>
-
-

3: Horizontal lazyload inside container example

-
+
+

3.1: Horizontal lazyload inside container example

+
  • Lazy load images example 3 image 1 @@ -290,6 +302,27 @@

    3: Horizontal lazyload inside container example

+

3.2: Vertical lazyload inside container example

+
+
    +
  • + Lazy load images example 3 image 1 +
  • +
  • + Lazy load images example 3 image 2 +
  • +
  • + Lazy load images example 3 image 3 +
  • +
+
+
+    var blazy = new Blazy({
+	container: '.container'
+    });
+			
+
+

4: Lazy load iframe example

@@ -302,7 +335,7 @@

4: Lazy load iframe example

</iframe>
-
+

5.1: Lazy load HTML5 video example

@@ -328,7 +361,7 @@

5.2: Lazy load HTML5 video advanced example

</video>
-
+

6: Lazy load script example

Check the console log

@@ -337,6 +370,7 @@

6: Lazy load script example

+ - + \ No newline at end of file diff --git a/package.json b/package.json index 812dcc4..d42a4d3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blazy", - "version": "1.6.2", + "version": "1.8.2", "description": "A fast lightweight pure JavaScript script for lazy loading and multi-serving images, iframes, videos and more.", "main": "blazy.js", "keywords": [ @@ -12,6 +12,8 @@ "lazyloading", "image", "images", + "picture", + "srcset", "iframe", "video", "unity", @@ -22,7 +24,7 @@ "author": "Bjørn Klinggaard (http://dinbror.dk/blazy)", "repository": { "type": "git", - "url": "https://github.com/dinbror/blazy.git" + "url": "git://github.com/dinbror/blazy.git" }, "bugs": { "url": "https://github.com/dinbror/blazy/issues" diff --git a/polyfills/closest.js b/polyfills/closest.js new file mode 100644 index 0000000..83c8f56 --- /dev/null +++ b/polyfills/closest.js @@ -0,0 +1,29 @@ +// Polyfill for Element.closest that falls back to Element.matches that falls back to querySelectorAll +// Created for blazy.js 1.8.1 - https://github.com/dinbror/blazy to ensure IE7+ support + + +(function () { + if (!Element.prototype.matches) { + Element.prototype.matches = + Element.prototype.matchesSelector || + Element.prototype.mozMatchesSelector || + Element.prototype.msMatchesSelector || + Element.prototype.oMatchesSelector || + Element.prototype.webkitMatchesSelector || + function(s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s), + i = matches.length; + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1; + }; + } + + if (!Element.prototype.closest) { + Element.prototype.closest = Element.prototype.closest || + function(selector) { + var element = this; + while (element.matches && !element.matches(selector)) element = element.parentNode; + return element.matches ? element : null; + }; + } +})(); \ No newline at end of file