Created
April 21, 2015 19:58
-
-
Save jdsharp/aeedb15320bef3d940c6 to your computer and use it in GitHub Desktop.
Hooks for lazy loading images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.isCloseToViewport = function(node, howClose) { | |
if ( !node ) { | |
return false; | |
} | |
var factor = howClose; | |
if ( !factor ) { | |
factor = 1; | |
} | |
var doc = node && node.ownerDocument && node.ownerDocument.documentElement; | |
var rect = node.getBoundingClientRect(); | |
var wh = window.innerHeight; | |
var sy = window.pageYOffset - doc.clientTop; | |
var h2 = (wh + sy) + (wh * factor); | |
if ( rect.top <= h2 ) { | |
return true; | |
} | |
return false; | |
}; | |
var scrollResizeCallbacks = []; | |
// inViewport custom event | |
window.attachScrollResize = function(callback) { | |
scrollResizeCallbacks.push(callback); | |
}; | |
window.detachScrollResize = function(callback) { | |
var i = scrollResizeCallbacks.indexOf(callback); | |
if ( i > -1 ) { | |
scrollResizeCallbacks.splice(i, 1); | |
return true; | |
} | |
return false; | |
}; | |
var checkScrollResizeTimer = null; | |
var checkScrollResize = function() { | |
clearTimeout(checkScrollResizeTimer); | |
checkScrollResizeTimer = setTimeout(function() { | |
for ( var i = 0; i < scrollResizeCallbacks.length; i++ ) { | |
setTimeout(scrollResizeCallbacks[i], 0); | |
} | |
}, 100); | |
}; | |
window.addEventListener('scroll', checkScrollResize); | |
window.addEventListener('resize', checkScrollResize); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
getInitialState: function() { | |
return { | |
inViewport : false | |
}; | |
}, | |
componentDidMount: function() { | |
setTimeout(function() { | |
if ( !this._checkPosition(true) ) { | |
attachScrollResize(this._checkPosition); | |
} | |
}.bind(this), 100); | |
}, | |
componentWillUnmount: function() { | |
if ( !this.state.inViewport ) { | |
detachScrollResize(this._checkPosition); | |
} | |
}, | |
_checkPosition: function(onMount) { | |
var node = React.findDOMNode(this); | |
if ( isCloseToViewport(node, 1) ) { | |
if ( onMount !== true ) { | |
detachScrollResize(this._checkPosition); | |
} | |
this.setState({ | |
inViewport : true | |
}); | |
return true; | |
} | |
return false; | |
}, | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment