-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimageloader.jquery.js
96 lines (86 loc) · 3 KB
/
imageloader.jquery.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
86
87
88
89
90
91
92
93
94
95
96
(function($){
/**
* run $('.image').imageLoader() to reload all images
*
* use images like
* <img class="image" src="{small src}"
* data-src300="{300px source}"
* data-src600="{600px source}"
* data-src900="{900px source}"
* ... />
*/
$.fn.imageLoader = function(options) {
// set default settings:
var settings = $.extend({
startSize: 300, /* the smalles image size */
stepSize: 300, /* the step size to the next image size */
prefix: 'src',
hideClass: 'hide',
imgPath: '',
complete: function(el, src) { return el; }
}, options );
var _getProps = function(el) {
var $el = $(el);
var width = $el.width();
var height = $el.height();
var ratio = window.devicePixelRatio || 1;
return {
el: el,
$el: $el,
data: $el.data(),
bgImage: el.style.backgroundImage,
max: Math.max(width, height) * ratio
};
};
var _load = function(el, src, callback) {
$(el).load(function() {
el.setAttribute('draggable', true);
if (typeof callback === 'function') { callback(el, src); }
});
if (el.complete) {
el.setAttribute('draggable', true);
if (typeof callback === 'function') { callback(el, src); }
}
};
var _getImageSrc = function(props) {
var current = settings.startSize;
var temp = props.data[settings.prefix + current];
var src = temp;
while (temp !== undefined && props.max >= current) {
current += settings.stepSize;
temp = props.data[settings.prefix + current];
if (temp !== undefined) {
src = temp;
}
}
return settings.imgPath + src;
};
var _handleWrapper = function(el) {
var props = _getProps(el);
var src = _getImageSrc(props);
if (props.bgImage !== '') {
el.style.backgroundImage = 'url("' + src + '")';
} else {
var $img = props.$el.find('img:eq(0)');
if ($img.length > 0) {
_load($img.get(0), src, settings.complete);
$img.attr('src', src);
}
}
};
var _handleImage = function(el) {
var props = _getProps(el);
var src = _getImageSrc(props);
_load(el, src, settings.complete);
props.$el.attr('src', src);
};
var _loadImage = function(i, el) {
if (el.tagName.toLowerCase() === "img") {
_handleImage(el);
} else {
_handleWrapper(el);
}
};
return this.each(_loadImage);
};
}(jQuery));