Skip to content

Commit

Permalink
Inject styles
Browse files Browse the repository at this point in the history
  • Loading branch information
stereobooster committed May 29, 2017
1 parent d4b3841 commit 0128f5b
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/LazyLoad.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/utils/css.js
Original file line number Diff line number Diff line change
@@ -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%;
}`;
14 changes: 14 additions & 0 deletions src/utils/injectCSS.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 0128f5b

Please sign in to comment.