-
Notifications
You must be signed in to change notification settings - Fork 16
/
jquery.defer.js
335 lines (277 loc) · 9.16 KB
/
jquery.defer.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*! JsDefer v1.0.0-alpha: http://github.com/BorisMoore/jsdefer and http://jsviews.com/jsviews */
/*
* Script loader, using the 'Deferred' pattern for async operations
* Two versions:
* - jquery.defer.js (this file): the jQuery plugin version of JsDefer
* - jsdefer.js: the jQuery-independent version of JsDefer
* Copyright 2013, Boris Moore
* Released under the MIT License.
*/
// This is jquery.defer.js: the jQuery plugin version of JsDefer
jQuery.defer || (function( $, window, undefined ) {
var document = window.document,
anchor = document.createElement("a"),
deferSettings, defer, ready, readyDefer,
scriptByUrl = {},
loadingScripts = [],
loadingSubScripts;
function absUrl( basePath, url ) {
if ( url.indexOf( "//" ) === -1 ) {
url = basePath + url;
}
return anchor.href = url;
// For IE without DOCTYPE - need use recursive regex along lines: parts = url.split( "/../" ); parts[0] = parts[0].slice( 0, parts[0].lastIndexOf("/") + 1 ); Use recursive regex; return parts.join("").toLowerCase();
}
function getBasePath( url ) {
return url.slice( 0, url.lastIndexOf("/") + 1 );
}
function makeArray( items ) {
return typeof items === "string" ? [ items ] : items;
}
function normalize( items, basePath ) {
if ( !items ) {
return 0;
}
items = makeArray( items );
var name, i = items.length;
while ( i-- ) {
name = items[ i ];
if ( !defer[ name ] ) {
items[ i ] = absUrl( basePath, name );
}
}
return items;
}
function getScriptDef( name, thisUrl ) {
var thisUrlKey,
scriptDef = defer[ name ];
if ( scriptDef ) {
return scriptDef;
}
thisUrl = absUrl( getBasePath( thisUrl || "" ), name );
thisUrlKey = thisUrl.toLowerCase();
return scriptByUrl[ thisUrlKey ] || (scriptByUrl[ thisUrlKey ] = { url: thisUrl });
}
$.extend({
defer: function( scriptName, options, basePath ) {
options = options || {};
var i, readyName, asyncLoad, result, prevPromise,
runWait = 0,
delayDomReady = options.delayDomReady || deferSettings.delayDomReady,
min = options.min || deferSettings.min,
scriptDef = getScriptDef( scriptName, basePath ),
url = scriptDef.url,
loadUrl = ( min && scriptDef.minUrl ) || scriptDef.url,
settings = $.extend( scriptDef, options ),
bare = settings.bare,
contains = settings.contains,
loaded = settings.loaded,
depends = settings.depends,
multiple = settings.multiple,
parentPromise = scriptDef.prntPrms,
promise = scriptDef.promise,
runCb, thisPromise, hasRun, hasRunPromise;
function run() {
var i, thisRunCb = runCb || scriptDef.runCb; // For multiple or composite scripts, callback was passed via scriptDef
if ( !(runWait--) ) {
if ( asyncLoad.state() !== "rejected" ) {
if ( parentPromise ) {
asyncLoad.resolve(
result ||
(scriptDef.result = result = thisRunCb.call( promise, $, options ))
);
} else if ( contains ) {
loadingSubScripts = [];
thisRunCb.call( promise, $, options );
i = contains.length;
// The following lines could be in debug build only...
//if ( loadingSubScripts.length !== i ) {
// throw url; //script definition error - number of contained scripts not equal to contains array length.
//}
while ( i-- ) {
getScriptDef( contains[ i ], url ).runCb = loadingSubScripts[ i ].run;
}
loadingSubScripts = 0;
hasRun.resolve();
loadDependencies( contains, [], function() {
i = contains.length;
result = [];
while ( i-- ) {
result.push( getScriptDef( contains[ i ], url ).result );
}
asyncLoad.resolve( result );
});
} else {
asyncLoad.resolve(
result ||
(scriptDef.result = result = bare ? "bare" : thisRunCb.call( promise, $, options ))
);
}
result = multiple ? 0 : result;
}
if ( delayDomReady ) {
ready( true );
}
}
}
function reject() {
asyncLoad.reject( "fail", url );
}
function loadDependencies( newDepends, promises, cb ) {
promises = promises || [];
var i = newDepends && newDepends.length;
while ( i-- ) {
promises.push( defer( newDepends[ i ], options, url ));
}
$.when.apply( $, promises ).fail( reject ).done( cb || run );
}
function getScript() {
return $.ajax({
url: loadUrl,
dataType: "script",
timeout: settings.timeout,
cache: !settings.noCache,
crossDomain: true // Force regular script insertion, rather than XMLHTTP plus script insertion in document, for easier debugging.
})
.fail( reject )
// readyStateChange complete has happened
.done( function() {
var deferRunSettings = bare ? 0 : loadingScripts.shift();
if ( !deferRunSettings ) {
if ( !bare ) {
// 404 or similar - no script got loaded for this url.
// This only works for IE. For Chrome and FF, neither done nor fail cb of $.ajax get called for 404.
// Set timeout to get error for all browsers.
reject();
}
// Non-wrapped script
run();
return;
}
runCb = scriptDef.runCb = deferRunSettings.run;
if ( deferRunSettings.def ) {
$.deferDef( deferRunSettings.def, url );
}
depends = makeArray( deferRunSettings.depends ) || [];
prepareSubDefs( !contains && deferRunSettings.contains )
if ( depends.length ) {
runWait++;
loadDependencies( depends );
}
});
}
function prepareSubDefs( containNames ) {
if ( containNames ) {
hasRun = $.Deferred();
hasRunPromise = [ hasRun.promise() ];
contains = makeArray( containNames );
i = contains.length;
while ( i-- ) {
getScriptDef( contains[ i ], url ).prntPrms = hasRunPromise;
}
}
}
if ( multiple || !promise ) {
asyncLoad = $.Deferred();
if ( loaded && eval( loaded ) ) {
return asyncLoad.resolve().promise();
}
if ( delayDomReady ) {
$.readyWait++;
}
prevPromise = promise;
asyncLoad = $.Deferred();
promise = scriptDef.promise = asyncLoad.promise();
if ( bare ) {
loadDependencies( depends, 0, getScript );
} else if ( prevPromise ) {
// This is a subsequent call, with multiple = true;
loadDependencies( 0, [ prevPromise ]);
} else if ( parentPromise ) {
loadDependencies( depends, parentPromise );
} else {
prepareSubDefs( contains );
loadDependencies( depends, [ getScript().promise() ] );
}
}
if ( readyName = options.readyName || scriptDef.name ) {
ready[ readyName ] = promise;
}
return promise;
},
deferDef: function( scriptDefs, thisUrl ) {
var scriptName, basePath, scriptDef,
scriptEl = document.getElementsByTagName( "script" );
function defineScript( name, newScriptDef ) {
// Autogenerate methods on defer for registered scripts.
if ( typeof newScriptDef === "string" ) {
newScriptDef = { url: newScriptDef };
}
var minUrl = newScriptDef.minUrl,
url = absUrl( basePath, newScriptDef.url ),
// May be some issues in Chrome. Investigate:
// scriptDef = scriptByUrl[ url ];
// // Autogenerate methods on defer for registered scripts.
// if ( !scriptDef ) {
// scriptDef = function() {
// var args = array.prototype.slice.call( arguments, 0 );
// args.unshift( name );
// return defer.apply( $, args );
// }
// }
// Autogenerate methods on defer for registered scripts.
scriptDef = scriptByUrl[ url ] || function() {
var args = Array.prototype.slice.call( arguments, 0 );
args.unshift( name );
return defer.apply( $, args );
};
newScriptDef.url = url;
if ( minUrl ) {
newScriptDef.minUrl = absUrl( basePath, minUrl );
}
$.extend( scriptDef, newScriptDef );
scriptByUrl[ url ] = defer[ name ] = scriptDef;
scriptDef.name = name;
}
// This if fine for static scripts and inline script, but will not find the correct script element, in the case of dynamically loaded scripts.
// So we require define to be loaded statically or in the page.
// But can pass a definition to run, in dynamically loaded pages - and use thisUrl.
scriptEl = scriptEl[ scriptEl.length-1 ];
basePath = getBasePath( thisUrl || scriptEl.src );
if ( typeof scriptDefs === "string" ) {
// Calling $.deferDef( nameOrAbsoluteUrlOrRelativeUrl) will return the scriptDef object
return defer[scriptDefs ] || scriptByUrl[ absUrl( basePath, scriptDefs )];
}
for ( scriptName in scriptDefs ) {
defineScript( scriptName, scriptDefs[ scriptName ] );
}
for ( scriptName in scriptDefs ) {
scriptDef = getScriptDef( scriptName );
scriptDef.depends = normalize( scriptDef.depends, basePath );
scriptDef.contains = normalize( scriptDef.contains, basePath );
}
},
deferSettings: {
delayDomReady: false,
min: true
}
});
window.$deferRun = function( run, settings ) {
settings = makeArray( settings );
settings = settings && settings.length ? { depends: settings } : settings || {};
settings.run = run;
( loadingSubScripts || loadingScripts ).push( settings );
};
deferSettings = $.deferSettings;
defer = $.defer;
ready = $.ready;
})( jQuery, window );
// TODO Add CSS loader support
//
//function loadStyles( src ) {
// var styles = document.createElement("link");
// styles.href = src.indexOf("http") === 0 ? src : basePath + src;
// styles.rel = "stylesheet";
// styles.type = "text/css";
// head.appendChild( styles );
//}