Skip to content

Commit 0128f5b

Browse files
committed
Inject styles
1 parent d4b3841 commit 0128f5b

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

src/LazyLoad.jsx

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import debounce from 'lodash/debounce';
66
import throttle from 'lodash/throttle';
77
import parentScroll from './utils/parentScroll';
88
import inViewport from './utils/inViewport';
9+
import injectCss from './utils/injectCSS';
10+
11+
injectCss(window);
912

1013
export default class LazyLoad extends Component {
1114
constructor(props) {
@@ -125,10 +128,22 @@ export default class LazyLoad extends Component {
125128
onError: () => { this.setState({ errored: true }); },
126129
};
127130

131+
let content;
132+
133+
if (visible) {
134+
if (loaded) {
135+
content = React.cloneElement(children, props);
136+
} else if (errored) {
137+
content = offline;
138+
} else {
139+
content = [spinner, React.cloneElement(children, props)]
140+
}
141+
}
142+
128143
return React.createElement(this.props.elementType, {
129144
className: elClasses,
130145
style: elStyles,
131-
}, visible && [spinner, offline, React.cloneElement(children, props)] );
146+
}, content);
132147
}
133148
}
134149

src/utils/css.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
export default `
2+
.LazyLoad img { opacity: 0; }
3+
.LazyLoad.is-loaded img { opacity: 1; }
4+
.LazyLoad {
5+
position: relative;
6+
height: 0;
7+
padding-bottom: 75%;
8+
overflow: hidden;
9+
}
10+
.LazyLoad iframe,
11+
.LazyLoad object,
12+
.LazyLoad embed,
13+
.LazyLoad video,
14+
.LazyLoad img {
15+
position: absolute;
16+
top: 0;
17+
left: 0;
18+
width: 100%;
19+
height: 100%;
20+
}`;

src/utils/injectCSS.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import cssRules from './css';
2+
3+
const injectCSS = (window) => {
4+
if (window && typeof window === 'object' && window.document) {
5+
const { document } = window;
6+
const head = (document.head || document.getElementsByTagName('head')[0]);
7+
8+
const styleElement = document.createElement('style');
9+
styleElement.innerHTML = cssRules;
10+
head.appendChild(styleElement);
11+
}
12+
};
13+
14+
export default injectCSS;

0 commit comments

Comments
 (0)