Skip to content

Instantly share code, notes, and snippets.

@mohdhazwan
Last active August 15, 2017 07:27
Show Gist options
  • Save mohdhazwan/84faee793b16ae8ae8949eb3ad97cc1f to your computer and use it in GitHub Desktop.
Save mohdhazwan/84faee793b16ae8ae8949eb3ad97cc1f to your computer and use it in GitHub Desktop.
simple Lazy Load written ES6 for React / Create React App
img {
opacity: 1;
transition: opacity 0.3s;
}
img[data-src] {
opacity: 0.5;
background: ANYCOLOR;
width: ANYHEIGHT;
height: ANYHEIGHT;
}
import React, {Components} from 'react'
import {tinyLazy} from './tinyLazy'
class Malas extends Components {
componentDidMount(){
window.addEventListener('scroll', tinyLazy);
tinyLazy()
}
componentWillUnmount(){
window.removeEventListener('scroll', tinyLazy);
}
render(){
return (
<main>
<img data-src="//source.unsplash.com/500x500" alt="" />
<img data-src="//source.unsplash.com/500x501" alt="" />
<img data-src="//source.unsplash.com/501x500" alt="" />
<img data-src="//source.unsplash.com/501x501" alt="" />
<img data-src="//source.unsplash.com/502x501" alt="" />
<img data-src="//source.unsplash.com/501x502" alt="" />
<img data-src="//source.unsplash.com/502x502" alt="" />
<img data-src="//source.unsplash.com/503x503" alt="" />
<img data-src="//source.unsplash.com/500x503" alt="" />
<img data-src="//source.unsplash.com/503x500" alt="" />
<img data-src="//source.unsplash.com/504x504" alt="" />
<img data-src="//source.unsplash.com/500x504" alt="" />
<img data-src="//source.unsplash.com/504x500" alt="" />
<img data-src="//source.unsplash.com/505x505" alt="" />
</main>
)
}
export default Malas
function isInViewport(el){
const rect = el.getBoundingClientRect();
return (
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (
window.innerHeight ||
document.documentElement.clientHeight) &&
rect.left <= (
window.innerWidth ||
document.documentElement.clientWidth)
);
}
export function tinyLazy(){
const lazy = document.querySelectorAll('img[data-src]');
for(let i=0; i<lazy.length; i++){
if(isInViewport(lazy[i])){
lazy[i].setAttribute('src', lazy[i].getAttribute('data-src'));
lazy[i].onload = function() {
lazy[i].removeAttribute('data-src');
};
}
}
}
@mohdhazwan
Copy link
Author

mohdhazwan commented Aug 15, 2017

Steps

  1. Add tinyLazy.js && css
  2. Import tinyLazy into your app
  3. Add data-src onto your images
  4. Done

Feel free to fork

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment