-
Notifications
You must be signed in to change notification settings - Fork 5
/
LoadAssets.js
85 lines (75 loc) · 2.68 KB
/
LoadAssets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var LoadAssets = React.createClass({
getInitialState: function () {
// 'loaded' state by default is false
return {loaded: false};
},
componentDidMount: function () {
var
_self = this,
totalAssets = this.props.assets.length,
loadedAssets = 0
;
// Start loading all the assets
Array.prototype.forEach.call(this.props.assets, function(asset) {
_self.loadAsset(asset.uri, function(e) {
loadedAssets++;
if (loadedAssets == totalAssets) {
// when all the assets are loaded set state 'loaded' to true
_self.setState({loaded: true});
// when all the assets are loaded call the callback function if any
if (typeof(_self.props.onLoad) === "function") _self.props.onLoad();
}
});
});
},
loadAsset: function(uri, callback) {
// preload if asset is image
if (uri.toLowerCase().match("jpg|jpeg|gif|png|webp") !== null) {
var image = new Image();
image.src = uri;
image.onload = callback;
}
// preload if asset is video
if (uri.toLowerCase().match("mp4|webm|ogv") !== null) {
var video = document.createElement('video');
var source = document.createElement('source');
source.src = uri;
video.setAttribute("preload", "auto");
video.appendChild(source);
video.addEventListener('canplaythrough', callback, false);
}
},
render: function() {
var output = [];
if (!this.state.loaded) {
// asset not loaded yet - loading UI
output.push(<div className="loading"></div>);
} else {
// asset fully loaded - show asset
var assets = this.props.assets.map(function(asset) {
var assetOutput;
// it's an image
if (asset.uri.toLowerCase().match("jpg|jpeg|gif|png|webp") !== null) {
assetOutput = (<img src={asset.uri} className={asset.className} />);
}
// it's a video
if (asset.uri.toLowerCase().match("mp4|webm|ogv") !== null) {
// TODO: make it smart so it will create a video element with many sources instead of many video elements for different video formats
assetOutput = (
<video className={asset.className} >
<source src={asset.uri} type={"video/" + asset.uri.toLowerCase().split('.').pop()} />
</video>
);
}
// adding props if any
if (asset.attributes !== undefined) {
Array.prototype.forEach.call(asset.attributes, function(a) {
assetOutput.props[Object.keys(a)[0]] = a[Object.keys(a)[0]];
});
}
output.push(assetOutput);
});
}
return (<div className="wrapper">{output}</div>);
}
});