diff --git a/src/LazyLoad.jsx b/src/LazyLoad.jsx index 1340182..d3d6909 100644 --- a/src/LazyLoad.jsx +++ b/src/LazyLoad.jsx @@ -6,6 +6,9 @@ import debounce from 'lodash/debounce'; import throttle from 'lodash/throttle'; import parentScroll from './utils/parentScroll'; import inViewport from './utils/inViewport'; +import injectCss from './utils/injectCSS'; + +injectCss(window); export default class LazyLoad extends Component { constructor(props) { @@ -125,10 +128,22 @@ export default class LazyLoad extends Component { onError: () => { this.setState({ errored: true }); }, }; + let content; + + if (visible) { + if (loaded) { + content = React.cloneElement(children, props); + } else if (errored) { + content = offline; + } else { + content = [spinner, React.cloneElement(children, props)] + } + } + return React.createElement(this.props.elementType, { className: elClasses, style: elStyles, - }, visible && [spinner, offline, React.cloneElement(children, props)] ); + }, content); } } diff --git a/src/utils/css.js b/src/utils/css.js new file mode 100644 index 0000000..435c980 --- /dev/null +++ b/src/utils/css.js @@ -0,0 +1,20 @@ +export default ` +.LazyLoad img { opacity: 0; } +.LazyLoad.is-loaded img { opacity: 1; } +.LazyLoad { + position: relative; + height: 0; + padding-bottom: 75%; + overflow: hidden; +} +.LazyLoad iframe, +.LazyLoad object, +.LazyLoad embed, +.LazyLoad video, +.LazyLoad img { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +}`; diff --git a/src/utils/injectCSS.js b/src/utils/injectCSS.js new file mode 100644 index 0000000..1512855 --- /dev/null +++ b/src/utils/injectCSS.js @@ -0,0 +1,14 @@ +import cssRules from './css'; + +const injectCSS = (window) => { + if (window && typeof window === 'object' && window.document) { + const { document } = window; + const head = (document.head || document.getElementsByTagName('head')[0]); + + const styleElement = document.createElement('style'); + styleElement.innerHTML = cssRules; + head.appendChild(styleElement); + } +}; + +export default injectCSS;