Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge upstream #1

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 40 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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**<br>
1. [Demo](https://github.com/dinbror/blazy#demo)<br>
2. [Usage & API](https://github.com/dinbror/blazy#how-to--api)<br>
2. [Usage & API](https://github.com/dinbror/blazy#usage--api)<br>
3. [Why be lazy?](https://github.com/dinbror/blazy#why-be-lazy)<br>
4. [Changelog](https://github.com/dinbror/blazy#changelog)<br>
5. [License](https://github.com/dinbror/blazy#license)<br>
Expand Down Expand Up @@ -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).

Expand Down
143 changes: 98 additions & 45 deletions blazy.js
Original file line number Diff line number Diff line change
@@ -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
*/
Expand All @@ -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) {
Expand All @@ -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;
Expand All @@ -69,23 +71,22 @@
/* 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) {
loadElement(element, force, opt);
});
}
};
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);
});
}
Expand Down Expand Up @@ -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) {
Expand All @@ -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--;
Expand All @@ -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();
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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) {
Expand All @@ -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;
}
Expand All @@ -284,15 +337,15 @@
if (ele.attachEvent) {
ele.attachEvent && ele.attachEvent('on' + type, fn);
} else {
ele.addEventListener(type, fn, false);
ele.addEventListener(type, fn, { capture: false, passive: true });
}
}

function unbindEvent(ele, type, fn) {
if (ele.detachEvent) {
ele.detachEvent && ele.detachEvent('on' + type, fn);
} else {
ele.removeEventListener(type, fn, false);
ele.removeEventListener(type, fn, { capture: false, passive: true });
}
}

Expand All @@ -314,4 +367,4 @@
fn.apply(scope, arguments);
};
}
});
});
Loading