├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
└── src
├── App.js
├── App.test.js
├── AppStyle.js
├── index.js
├── logo.svg
└── serviceWorker.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A modern image gallery with React Suspense
2 |
3 | 
4 |
5 | This is an image gallery that lazy loads images on the fly upon scrolling, but is also capable of showing a low resolution version of the desired image while waiting for the asynchronous high resolution image delivery. This allows us to show a downscaled version of the image for users with slower network speeds, thus providing a better and more appealing user experience.
6 |
7 | ### Run
8 |
9 | ```sh
10 | $ cd react-suspense-image-loader
11 | $ npm i
12 | $ npm start
13 | ```
14 |
15 |
16 |
17 |
18 | License
19 | ----
20 |
21 | MIT
22 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-suspense-lazy-image-loader",
3 | "version": "0.1.0",
4 | "private": true,
5 | "license": "(MIT OR Apache-2.0)",
6 | "dependencies": {
7 | "react": "^16.6.3",
8 | "react-cache": "^2.0.0-alpha.1",
9 | "react-dom": "^16.6.3",
10 | "react-inview-monitor": "^2.2.0",
11 | "react-scripts": "2.1.1",
12 | "styled-components": "^4.1.1"
13 | },
14 | "scripts": {
15 | "start": "react-scripts start",
16 | "build": "react-scripts build",
17 | "test": "react-scripts test",
18 | "eject": "react-scripts eject"
19 | },
20 | "eslintConfig": {
21 | "extends": "react-app"
22 | },
23 | "browserslist": [
24 | ">0.2%",
25 | "not dead",
26 | "not ie <= 11",
27 | "not op_mini all"
28 | ]
29 | }
30 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andrisgauracs/react-suspense-image-loader/422c1cb48a1c64404b81aa16aa9a8e9592318760/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React Suspense Lazy Image Loader
23 |
24 |
25 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component, Suspense } from 'react';
2 | import { unstable_createResource } from 'react-cache';
3 | import styled, { createGlobalStyle } from 'styled-components';
4 | import InViewMonitor from 'react-inview-monitor';
5 | import * as Style from './AppStyle';
6 | import logo from './logo.svg';
7 |
8 |
9 | /* Moved the CreateReactApp default css style to
10 | a styled-components globalStyle variable.
11 | This just appends this style to the whole document */
12 | const GlobalStyle = createGlobalStyle`
13 | body {
14 | margin: 0;
15 | padding: 0;
16 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
17 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
18 | sans-serif;
19 | -webkit-font-smoothing: antialiased;
20 | -moz-osx-font-smoothing: grayscale;
21 | }
22 |
23 | code {
24 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
25 | monospace;
26 | }
27 | `;
28 |
29 | /* We utilize the createResource provied by React,
30 | which allows to access the image data asynchronously */
31 | const ImageResource = unstable_createResource(
32 | source =>
33 | new Promise(resolve => {
34 | const img = new Image();
35 | img.src = source;
36 | img.onload = resolve;
37 | })
38 | );
39 |
40 | /* We create a new img component, that will read and display
41 | the full resolution picture from the cache, once it gets loaded */
42 | const Img = ({ src, alt, ...props }) => {
43 | ImageResource.read(src);
44 | return
45 | }
46 |
47 | const ImageContainer = styled.div`
48 | width:500px;
49 | height:281px;
50 | display:block;
51 | border-radius:10px;
52 | margin-bottom:20px;
53 | overflow:hidden;
54 | position:relative;
55 | img {
56 | width:100%;
57 | }
58 | .blurry {
59 | filter:blur(10px);
60 | position:absolute;
61 | top:0;
62 | left:0;
63 | width:100%;
64 | height:100%;
65 | z-index:2;
66 | }
67 | `;
68 |
69 | /* an image wrapper component, that holds
70 | all of our data inside it, plus it
71 | get triggered to run only when scrolled into view. */
72 | const ImageWrapper = ({ image, nr, render }) => (
73 | render ?
74 |
75 | {/* This gets shown while the full res image is preloading */}
77 |
78 | {/* This gets shown below while the low res image is preloading */}
79 | {'Loading...'}
80 |
81 | }>
82 |
83 | {/* This gets shown when the full res image is finally loaded */}
84 |
85 |
86 |
87 |
88 | :
89 |
90 | );
91 |
92 | class App extends Component {
93 | constructor(props) {
94 | super(props);
95 | const files = [];
96 | for (let i = 0; i < 20; i++) {
97 | let pictureNr = Math.floor(Math.random() * 100);
98 | files.push({large: `https://picsum.photos/1920/1080/?image=${pictureNr}`, small: `https://picsum.photos/200/113/?image=${pictureNr}`})
99 | }
100 | this.state = {
101 | images: files
102 | }
103 | }
104 | render() {
105 | return (
106 |
107 |
108 |
109 |
110 | {`React Suspense Lazy Image Loader`}
111 | {(this.state.images.map((e,i)=>
112 |
113 | ))}
114 |
115 |
116 | );
117 | }
118 | }
119 |
120 | export default App;
121 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render(, div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/AppStyle.js:
--------------------------------------------------------------------------------
1 | import styled, { keyframes } from 'styled-components';
2 |
3 | export const loaderAnimation = keyframes`
4 | 0%,
5 | 80%,
6 | 100% {
7 | box-shadow: 0 2.5em 0 -1.3em;
8 | }
9 | 40% {
10 | box-shadow: 0 2.5em 0 0;
11 | }
12 | `;
13 |
14 | export const logoSpin = keyframes`
15 | from {
16 | transform: rotate(0deg);
17 | }
18 | to {
19 | transform: rotate(360deg);
20 | }
21 | `;
22 |
23 | export const AppHeader = styled.header`
24 | background-color: #282c34;
25 | min-height: 100vh;
26 | display: flex;
27 | flex-direction: column;
28 | align-items: center;
29 | justify-content: center;
30 | font-size: calc(10px + 2vmin);
31 | color: white;
32 | `;
33 |
34 | export const AppLogo = styled.img`
35 | animation: ${logoSpin} infinite 20s linear;
36 | height: 100px;
37 | `;
38 |
39 | export const Title = styled.h2`
40 | font-size:24px;
41 | margin-bottom:80px;
42 | `;
43 |
44 | export const Loader = styled.div`
45 | position:absolute;
46 | top:0;
47 | bottom:0;
48 | right:0;
49 | left:0;
50 | margin:auto;
51 | border-radius: 50%;
52 | width: 2.5em;
53 | height: 2.5em;
54 | animation-fill-mode: both;
55 | animation: ${loaderAnimation} 1.8s infinite ease-in-out;
56 | &:before,
57 | &:after {
58 | border-radius: 50%;
59 | width: 2.5em;
60 | height: 2.5em;
61 | animation-fill-mode: both;
62 | animation: ${loaderAnimation} 1.8s infinite ease-in-out;
63 | }
64 | color: #ffffff;
65 | font-size: 10px;
66 | margin: 80px auto;
67 | position: relative;
68 | text-indent: -9999em;
69 | -webkit-transform: translateZ(0);
70 | -ms-transform: translateZ(0);
71 | transform: translateZ(0);
72 | -webkit-animation-delay: -0.16s;
73 | animation-delay: -0.16s;
74 | &:before,
75 | &:after {
76 | content: '';
77 | position: absolute;
78 | top: 0;
79 | }
80 | &:before {
81 | left: -3.5em;
82 | -webkit-animation-delay: -0.32s;
83 | animation-delay: -0.32s;
84 | }
85 | &:after {
86 | left: 3.5em;
87 | }
88 | `;
89 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 | import * as serviceWorker from './serviceWorker';
5 |
6 | ReactDOM.render(, document.getElementById('root'));
7 |
8 | // If you want your app to work offline and load faster, you can change
9 | // unregister() to register() below. Note this comes with some pitfalls.
10 | // Learn more about service workers: http://bit.ly/CRA-PWA
11 | serviceWorker.unregister();
12 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------