Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use XMLHttpRequest to load image and get progress #29

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/node_modules/
/lib/
npm-debug.log
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
node:
babel --stage=0 src --out-dir lib
./node_modules/.bin/babel --stage=0 src --out-dir lib

browser:
babel-node ./node_modules/.bin/webpack --config ./webpack.config.js
./node_modules/.bin/babel-node ./node_modules/.bin/webpack --config ./webpack.config.js

build: node browser

test:
babel-node ./test/server.js
./node_modules/.bin/babel-node ./test/server.js

dev:
babel-node ./test/server.js --open
./node_modules/.bin/babel-node ./test/server.js --open

major:
mversion major
Expand Down
66 changes: 51 additions & 15 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ export default class ImageLoader extends React.Component {

constructor(props) {
super(props);
this.state = {status: props.src ? Status.LOADING : Status.PENDING};
this.state = {
status: props.src ? Status.LOADING : Status.PENDING,
imageSrc: props.src,
progress: 0,
};
}

componentDidMount() {
Expand All @@ -47,7 +51,7 @@ export default class ImageLoader extends React.Component {
}

componentDidUpdate() {
if (this.state.status === Status.LOADING && !this.img) {
if (this.state.status === Status.LOADING && !this.request) {
this.createLoader();
}
}
Expand All @@ -65,25 +69,56 @@ export default class ImageLoader extends React.Component {
createLoader() {
this.destroyLoader(); // We can only have one loader at a time.

this.img = new Image();
this.img.onload = ::this.handleLoad;
this.img.onerror = ::this.handleError;
this.img.src = this.props.src;
this.request = new XMLHttpRequest();
this.request.onloadstart = ::this.handleProgressStart;
this.request.onprogress = ::this.handleProgress;
this.request.onloadend = ::this.handleProgressEnd;
this.request.onload = ::this.handleLoad;
this.request.open('GET', this.props.src, true);
this.request.withCredentials = true;
this.request.responseType = 'blob';
this.request.send(null);
}

destroyLoader() {
if (this.img) {
this.img.onload = null;
this.img.onerror = null;
this.img = null;
if (this.request) {
this.request.onloadstart = null;
this.request.onprogress = null;
this.request.onloadend = null;
this.request.onload = null;
this.request = null;
}
}

handleLoad(event) {
this.destroyLoader();
this.setState({status: Status.LOADED});
const response = event.target;
const imageSrc = typeof window !== 'undefined' ?
window.URL.createObjectURL(this.request.response) : this.props.src;

if (response.readyState !== 4 || response.status < 200 || response.status > 300) {
return this.handleError(response);
}

this.setState({status: Status.LOADED, progress: 1, imageSrc});
if (this.props.onLoad) this.props.onLoad(event);
this.destroyLoader();
}

handleProgress({lengthComputable, loaded, total}) {
if (lengthComputable) {
return;
}
const progress = (loaded / total).toFixed(2);

this.setState({progress});
}

handleProgressStart() {
this.setState({progress: 0});
}

handleProgressEnd() {
this.setState({progress: 1});
}

handleError(error) {
Expand All @@ -94,8 +129,9 @@ export default class ImageLoader extends React.Component {
}

renderImg() {
const {src, imgProps} = this.props;
let props = {src};
const {imgProps} = this.props;
const {imageSrc} = this.state;
let props = {src: imageSrc};

for (let k in imgProps) {
if (imgProps.hasOwnProperty(k)) {
Expand Down Expand Up @@ -127,7 +163,7 @@ export default class ImageLoader extends React.Component {
break;

default:
if (this.props.preloader) wrapperArgs.push(this.props.preloader());
if (this.props.preloader) wrapperArgs.push(this.props.preloader(this.state.progress));
break;
}

Expand Down
2 changes: 1 addition & 1 deletion standalone/react-imageloader.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ describe('ReactImageLoader', () => {
assert(TestUtils.findRenderedDOMComponentWithTag(loader, 'div'));
});

it('calls progress function with progress value as first argument if provided', async function() {
const preloader = (progress) => { assert.equal(progress, 0, 'Expected progress value as an argument'); };
await loadImage({src: nocache('tiger.svg'), preloader});
});

it('removes a preloader when load completes', async function() {
const loader = await loadImage({src: nocache('tiger.svg'), preloader: React.DOM.div});
assert.throws(() => { TestUtils.findRenderedDOMComponentWithTag(loader, 'div'); });
Expand Down Expand Up @@ -142,7 +147,7 @@ describe('ReactImageLoader', () => {
/>, domEl);

// Make sure that the image load isn't handled by ImageLoader.
loader.img.addEventListener('load', () => {
loader.request.addEventListener('load', () => {
assert.throws(() => TestUtils.findRenderedDOMComponentWithTag(loader, 'img'));
done();
});
Expand Down
2 changes: 1 addition & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default {
libraryTarget: 'umd',
target: 'web',
},
externals: ['React', {react: 'React'}],
externals: ['react', {react: 'React'}],
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel?stage=0'},
Expand Down