-
Notifications
You must be signed in to change notification settings - Fork 17
/
jsdefer.js
597 lines (513 loc) · 16.1 KB
/
jsdefer.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/*! 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:
* - jsdefer.js (this file): the jQuery-independent version of JsDefer
* - jquery.defer.js: the jQuery plugin version of JsDefer
* Copyright 2013, Boris Moore
* Released under the MIT License.
*/
// This is jsdefer.js: the jQuery-independent version of JsDefer
window.jsDefer || window.jQuery && jQuery.defer || (function( window, undefined ) {
var $, document = window.document,
anchor = document.createElement("a"),
deferSettings, defer, deferDef, ready, readyList,
scriptByUrl = {},
loadingScripts = [],
loadingSubScripts,
promiseMethods = "then done fail state promise".split( " " ),
slice = [].slice;
if ( window.jQuery ) {
////////////////////////////////////////////////////////////////////////////////////////////////
// jQuery is loaded, so make $ the jQuery object
$ = jQuery;
// Workaround, to expose domReady promise. (Only needed because the Dom Ready promise is not exposed by core).
$( function() {
readyList.resolveWith( document , [ $ ] );
});
} else {
////////////////////////////////////////////////////////////////////////////////////////////////
// jQuery is not loaded. Make $ the jsDefer object
// Use a 'clone' of the implementation of Deferred from jQuery-1.10.0.js
// to provide identical Deferred APIs and behavior to jQuery.
// Also provide simplified support for $.extend, DomReady and AJAX x-domain requests,
// since we can't use jQuery implementations of those...
window.jsDefer = window.$ = $ = function( cb ) {
return readyList.done( cb );
};
$.extend = function( target, source ) {
if ( source === undefined ) {
source = target;
target = $;
}
for ( var name in source ) {
target[ name ] = source[ name ];
}
return target;
};
$.extend({
readyWait: 1,
ready: function( wait ) {
// A third-party is pushing the ready event forwards
if ( wait === true ) {
$.readyWait--;
}
if ( !$.readyWait || (wait !== true && !$.isReady) ) {
readyList.resolveWith( document , [ $ ] );
}
},
isFunction: function( elem ) {
return typeof elem === "function";
},
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
if ( elem instanceof Array ) {
deferred.done.apply( deferred, elem );
} else if ( $.isFunction( elem )) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = $._Deferred(),
failDeferred = $._Deferred(),
promise;
// Add errorDeferred methods, then and promise
$.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj , i /* internal */ ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
}
return obj;
}
} );
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && $.isFunction( firstParam.promise ) ?
firstParam :
$.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, slice.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && $.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
}
});
function getAjax( options ) {
var deferred = $.Deferred(),
head = document.getElementsByTagName( "head" )[ 0 ] || document.documentElement,
script = document.createElement( "script" );
script.src = options.url;
// TODO? Add support for timeout and cache
script.onload = script.onreadystatechange = function() {
if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
deferred.resolve();
}
};
head.insertBefore( script, head.firstChild );
return deferred;
};
}
////////////////////////////////////////////////////////////////////////////////////////////////
// The following code is identical to the corresponding code in jquery.defer.js
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.isRejected() ) {
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() {
// Use $.ajax if jQuery is loaded. Otherwised use our stripped down getAjax call.
return ($.ajax || getAjax)({
url: loadUrl,
dataType: "script",
timeout: options.timeout,
cache: !options.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
if ( window.jQuery && $ !== jQuery ) {
// Special case: jQuery has been loaded dynamically by JsDefer, so switch to plugin version of JsDefer
$ = jQuery.extend({
defer: defer,
deferSettings: deferSettings,
deferDef: deferDef
});
}
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( depends, [ 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 = 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;
deferDef = $.deferDef;
ready = $.ready;
readyList = $.Deferred();
readyList.promise( ready );
if ( !window.jQuery ) {
function domReady() {
if ( !document.body ) {
return setTimeout( function() {
domReady();
}, 1 );
}
$.isReady = true;
$.ready( true );
}
domReady();
}
})( window );