-
Notifications
You must be signed in to change notification settings - Fork 3
/
load_image.js
56 lines (47 loc) · 1.17 KB
/
load_image.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
;(function($, undefined){
'use strict';
// Provides this syntax:
//
// $(img).loadImage(someUrl);
//
$.fn.loadImage = function(newSrc) {
var img = this,
promise = $.Deferred();
var successCallback = function(){
img.unbind('load', successCallback);
img.unbind('error', failureCallback);
promise.resolve(img);
}
var failureCallback = function(){
img.unbind('load', successCallback);
img.unbind('error', failureCallback);
promise.reject(img);
}
img.bind('error', failureCallback);
img.bind('load', successCallback);
img.attr('src', newSrc);
// If the url is is cached and loaded,
// call the callback by hand.
//
if (img[0].complete || img[0].readyState) {
successCallback();
}
// Return the promise
//
return promise;
}
// Provides two additional syntaxes:
//
// $.loadImage(imgEl, someUrl);
// $.loadImage(someUrl);
//
$.loadImage = function(img, newSrc) {
if ($.type(newSrc) == 'undefined') {
var newSrc = img,
img = $('<img />');
} else {
var img = $(img);
}
return img.loadImage(newSrc);
}
}(jQuery));