-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
95 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"name": "imageLoader", | ||
"version": "0.0.1", | ||
"main": "imageloader.js", | ||
"description": "图片预加载函数" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
var __id = 0; | ||
|
||
function getId() { | ||
return ++__id; | ||
} | ||
|
||
function noop() { | ||
|
||
} | ||
|
||
function loadImage(images, callback, timeout) { | ||
var key, item, count, success, timeoutId, isTimeout; | ||
|
||
count = 0; | ||
success = true; | ||
isTimeout = false; | ||
|
||
callback = callback || noop; | ||
for (key in images) { | ||
if (!images.hasOwnProperty(key)) | ||
continue; | ||
item = images[key]; | ||
|
||
if (typeof (item) == 'string') { | ||
item = images[key] = { | ||
src: item | ||
}; | ||
} | ||
|
||
if (!item || !item.src) | ||
continue; | ||
|
||
count++; | ||
item.id = '__img_' + key + getId(); | ||
item.img = window[item.id] = new Image(); | ||
|
||
doLoad(item); | ||
} | ||
|
||
if (!count) { | ||
callback(success); | ||
} else if (timeout) { | ||
timeoutId = setTimeout(onTimeout, timeout); | ||
} | ||
|
||
function doLoad(item) { | ||
var img = item.img, | ||
id = item.id; | ||
|
||
item.status = "loading"; | ||
|
||
img.onload = function () { | ||
success = success && true; | ||
item.status = "loaded"; | ||
done(); | ||
}; | ||
img.onerror = function () { | ||
success = false; | ||
item.status = "error"; | ||
done(); | ||
}; | ||
img.src = item.src; | ||
|
||
function done() { | ||
img.onload = img.onerror = null; | ||
|
||
try { | ||
delete window[id]; | ||
} | ||
catch (e) { | ||
|
||
} | ||
if (!--count && !isTimeout) { | ||
clearTimeout(timeoutId); | ||
callback(success); | ||
} | ||
} | ||
} | ||
|
||
function onTimeout() { | ||
isTimeout = true; | ||
callback(false); | ||
} | ||
} | ||
|
||
module.exports = loadImage; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters