-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.preload.js
61 lines (51 loc) · 1.71 KB
/
jquery.preload.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
/*
* jQuery Preload - v0.1.0
* Tiny image preloader using deferred's promise object.
* https://github.com/yefremov/jquery-preload
*
* Copyright (c) 2012 Anton Yefremov
* Free to use and abuse under the MIT license.
* http://opensource.org/licenses/MIT
*/
(function ( factory ) {
'use strict';
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module
define( ['jquery'], factory );
} else {
// Browser globals
factory( jQuery );
}
} (function ( $ ) {
'use strict';
// Static method
$.preload = function ( sources ) {
var queue = $.Deferred()
, data = $.map( sources, function ( source ) {
var part = $.Deferred()
, image = $( '<img />' );
// Call progress callback on queue
part.done( queue.notify );
// Resolve on error / load / onreadystatechange (IE)
image.on( 'error load onreadystatechange', part.resolve ).attr( 'src', source );
// Return a part promise object
return part.promise();
});
// Resolve when all parts are done
$.when.apply( this, data ).done( queue.resolve );
// Return a queue promise object (then, done, fail, always, pipe, progress, and state)
return queue.promise();
};
// Collection method
$.fn.preload = function () {
var collection = this
// Find all image elements
, elements = collection.find( '[src]' ).add( collection.filter('[src]') )
// Map image elements to sources
, sources = elements.map(function () {
return this.getAttribute( 'src' );
});
// Preload and return a queue promise object (then, done, fail, always, pipe, progress, and state)
return $.preload( sources );
};
}));