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

Dom mutations support #1

Open
wants to merge 5 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
5 changes: 5 additions & 0 deletions src/LazyLoad.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const throttle = require('lodash.throttle');

const parentScroll = require('./utils/parentScroll');
const inViewport = require('./utils/inViewport');
const mutationsObserver = require('./utils/domObserver');

class LazyLoad extends Component {
constructor(props) {
Expand Down Expand Up @@ -36,7 +37,9 @@ class LazyLoad extends Component {
}

add(window, 'resize', this.lazyLoadHandler);
add(window, 'load', this.lazyLoadHandler);
add(eventNode, 'scroll', this.lazyLoadHandler);
mutationsObserver.registerCallback(this.lazyLoadHandler);
}

componentWillReceiveProps() {
Expand Down Expand Up @@ -100,7 +103,9 @@ class LazyLoad extends Component {
const eventNode = this.getEventNode();

remove(window, 'resize', this.lazyLoadHandler);
remove(window, 'load', this.lazyLoadHandler);
remove(eventNode, 'scroll', this.lazyLoadHandler);
mutationsObserver.unregisterCallback(this.lazyLoadHandler);
}

render() {
Expand Down
37 changes: 37 additions & 0 deletions src/utils/domObserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

let _observer = null;

const _callbacks = [];
const _observerConfig = { childList: true, subtree: true };

function _executeCallbacks() {
_callbacks.forEach((cb) => {
try {
cb();
} catch (ex) { } // eslint-disable-line no-empty
});
}
/**
* If browser supports the feature, create a unique observer that listens
* for DOM changes, and executes the registered callbacks (_callbacks).
*/
if (typeof MutationObserver !== 'undefined') {
_observer = new MutationObserver(_executeCallbacks);
_observer.observe(document.body, _observerConfig);
} else {
// IE10 and IE9 fallback
document.body.addEventListener('DOMSubtreeModified', _executeCallbacks);
}

export function registerCallback(cb) {
if (_callbacks.indexOf(cb) !== -1) {
_callbacks.push(cb);
}
}

export function unregisterCallback(cb) {
const idx = _callbacks.indexOf(cb);
if (idx !== -1) {
_callbacks.splice(idx, 1);
}
}