/
relyJS.js
825 lines (728 loc) · 18.7 KB
/
relyJS.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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/**
* relyJS
* @version 0.0.20110604
* @author Neekey <ni184775761@gmail.com>
* @description a imporved version of importJS
*/
(function() {
/**
* Base namespace for the framework
*/
this.$r = { _$r: this.$r };
/**
* private & publick utilities for the framework to use
* this utilities must be mutual independence
*/
var util = {
/*
* AJAX
* httpRequest used for load resource ( every string files )
* @param {String} url
* @param {Function} [callback]
* @param {Any} [userData] custom data passed to callback
*/
httpRequest: function( url, callback, userData ) {
// create XMLHttpRequest object
var xhr = window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' );
// set callcack
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
// Determine the data type
var t = xhr.getResponseHeader( 'content-type' ), err, data;
if ( xhr.status < 200 ) {
// 1xx informational response;
return;
}
else if ( xhr.status >= 300 ) {
// 3xx Redirection
// 4xx Client error
// 5xx Server error
err = xhr.status;
}
// else 2xx successful response;
else {
// if XML
if ( t === 'application/xml' )
data = xhr.responseXML;
// if JSON
else if ( t === 'application/json' )
data = JSON.parse( xhr.responseText );
// Other
else
data = xhr.responseText;
}
callback( err, data, xhr, userData );
}
};
xhr.open( 'GET', url, true );
xhr.send();
},
/**
* image loader
* @param {String} url
* @param {Function} [callback]
* @param {Any} [userData] custom data passed to callback
*/
imgLoader: function( url, callback, userData ) {
var _imgLoader = arguments.callee,
// for closure use
_this = this,
// create Image object
imgObj = new Image();
// if it is the first call to this method, set callback
if( !_imgLoader._onload ) {
_imgLoader._onload = function( e ) {
_imgLoader._oncomplete( this, 'load' );
};
_imgLoader._onerror = function( e ) {
_imgLoader._oncomplete( this, 'error' );
};
_imgLoader._onabort = function( e ) {
_imgLoader._oncomplete( this, 'abort' );
};
_imgLoader._oncomplete = function( img, type ) {
var err, xhr;
if ( type == 'error' || type == 'abort' ) {
err = 'img: ' + url + '[loadError]';
}
callback( err, img, xhr, userData );
};
}
// set callback to img
imgObj.onload = _imgLoader._onload;
imgObj.onabort = _imgLoader._onabort;
imgObj.onerror = _imgLoader._onerror;
imgObj.src = url;
},
/**
* handle url , convert to Absolute url
* @private
* @param {String} url
* @param {String} [localPath] Reference url
* @returns {String}
*/
handleUrl: function( url, localPath ) {
var URL_EX = /^http\:\/\/.+$|^https\:\/\/.+$/,
spaceEx = /^(\s+)|(\s+)$/g;
// get url... remove alias if exist
url = ( url || '' )
.replace( spaceEx, '' )
.split( /\s+/ )[ 0 ];
// if url is an absolute url
if ( URL_EX.test( url ) ) {
return url;
}
else {
// backup the protocol 'http' part, for rebuilding url
var httpStr = localPath.substring( 0, localPath.indexOf( "://" ) + 3);
// remove the protocol part and file name part of the url, include‘/’
localPath = localPath.substring(
localPath.indexOf("://") + 3, localPath.lastIndexOf("/"));
// Use '/ ' partition of the url
var localArray = localPath.split("/");
var urlArray = url.split("/");
while ( urlArray.length > 0 ) {
// if "..",pop() localArray
if ( urlArray[ 0 ] === ".." ) {
localArray.pop();
}
else{
localArray.push( urlArray[ 0 ] );
}
// remove the first elem of urlArray
urlArray.splice( 0, 1 );
}
// rebuild new url
var urlHandled = httpStr;
for ( var i = 0; i < localArray.length; i++ ) {
if( i !== ( localArray.length - 1 ) ) {
urlHandled += ( localArray[ i ] + "/" );
}
else{
urlHandled += localArray[ i ];
}
}
return urlHandled;
}
},
/**
* Check whether the specified string in the array
* @param {Array} arr whose elems are all string
* @param {String} str
* @param {Boolean}
*/
inStringArray: function( arr, str ){
if( arr.constructor == Array && typeof str == 'string' ){
var arrStr = arr.join( ' @ ' );
if( arrStr.indexOf( str ) >= 0 ){
return true;
}
}
return false;
}
}
/**
* private member( method & attribute )
*/
var pri = {
/**
* configuration for the framework
* rely: 'relay'
* scriptSuffix: ['js']
* imageSuffix: ['png', 'gif', 'jpg', 'bmp']
*/
config: {
scriptSuffix: ['js'],
dataSuffix: ['json', 'hmtl'],
imageSuffix: ['png', 'gif', 'jpg', 'bmp'],
log: true
},
/**
* log, record info about loading
*/
logList: [],
/**
* status of load
* finished
* loading
* initializing
*/
status: 'initializing',
/**
* Resource collection unit list
* every time $r.load is called, an new Resource collection unit will be add to the list
* Resource collection unit:
* type: script | data | image
* url: [ 'http://neekey.net/importJS.js', 'http://google.com/b.js' ] - resource absolute url
* rely: [], - rely resource absolute url
* status: 'loading'
* alias: 'module', - the name of this collection, optional
* callback: fn,
* userData: , - custom data pass to callback
*/
rcuList: [],
/**
* loading list
* url: status
* type: script | data | image
*/
loadingList: {},
/**
* finished resource list
* url: {
* data: resData,
* type: script | image | data
* }
*/
finishedList: {},
/**
* once a script resource been execued , it will be add to this list
* url: ifexecued
*/
scriptList: {},
/**
* A map from resource url to its alias
* url: alias
*/
aliasList: {},
/**
* module list, every call of $r.load corresponds to an module
* if 'alias' specified in $r.load, it will be the name of the module,
* else the module name will be automatically generated, such as 'module_1'
*/
moduleList: {},
/**
* used for generate module alias
*/
moduleAliasPrefix: 'module_',
moduleAliasCounter: 0,
/**
* add info to the loglist
*/
log: function( type, info ){
this.logList.push( [ type, info ] );
if( console && console.log && this.config.log ){
console.log( '[ ' + type + ' ] ' + info );
}
},
/**
* error handle
*/
errorHandle: function( type, msg ){
this.log( type, msg );
if( type == 'error' ){
throw 'Error occurs! ' + msg;
}
},
/**
* get alias by analysize url
*/
getAlias: function( url ){
var spaceEx = /^(\s+)|(\s+)$/g;
url = ( url || '' )
.replace( spaceEx, '' )
.split( /\s+/ )[ 1 ];
return url ? url : '';
},
/**
* initialize resource collection unit
*/
initRcu: function( o ){
var i;
// o.status = 'wait';
// add rely to url
o.url = o.rely.concat( o.url );
// push to rcuList
this.rcuList.push( o );
// add url to loadingList
this.addLoadingList( o.url );
this.log( 'info', 'a new resource collection unit has been initialized!' );
},
/**
* Traverse loadingList to load resource
*/
loadResource: function(){
var i, lolist = this.loadingList,
_this = this,
callback = function(){
_this.loadCallback.apply( _this, arguments );
};
// Traverse loadingList
for( i in lolist ){
if( lolist[ i ].status == 'wait' ){
if( lolist[ i ].type == 'image' ){
// load image
util.imgLoader( i, callback, { url: i, type: lolist[ i ].type } );
this.log( 'info', 'request image: ' + i );
}
else {
util.httpRequest( i, callback, { url: i, type: lolist[ i ].type } );
this.log( 'info', 'request script|data: ' + i );
}
// set status to 'loading'
lolist[ i ].status = 'loading';
}
}
},
/**
* load callback
*/
loadCallback: function( err, data, xhr, userData ){
var t = userData.type,
u = userData.url,
i, j, k, relyList, relyTag = false, alias;
if( !err ){
this.log( 'info', 'resource loaded: ' + u );
if( t != 'image' ){
// get rely files
relyList = this.getRely( data );
// handle url to absolute, and get alias
for( i = 0; relyList[ i ]; i++ ){
alias = this.getAlias( relyList[ i ] );
relyList[ i ] = util.handleUrl( relyList[ i ], u );
if( alias != '' ){
this.aliasList[ alias ] = relyList[ i ];
}
}
// insert relyList before resource whose url is u
for( i = 0; this.rcuList[ i ]; i++ ){
for( j = 0; this.rcuList[ i ].url[ j ]; j++ ){
if( this.rcuList[ i ].url[ j ] == u ){
relyTag = true;
// insert
for( k = 0; relyList[ k ]; k++ ){
this.rcuList[ i ].url.splice( j, 0, relyList[ k ] );
j++;
}
}
}
if( relyTag ){
// push relyList into rcuList[ i ].rely
for( j = 0; relyList[ j ]; j++ ){
// check wether relyList[ i ] in this.rcuList[ i ].rely
if( !util.inStringArray( this.rcuList[ i ].rely, relyList[ j ] ) ){
this.rcuList[ i ].rely.push( relyList[ j ] );
}
}
}
}
// add relylist to loadingList
this.addLoadingList( relyList );
}
}
else {
this.errorHandle( 'warning', 'resource load failed: ' + u );
}
// remove from loadingList
delete this.loadingList[ u ];
// add to finishedList
this.finishedList[ u ] = {
data: data,
type: t,
err: err
};
// Through the array to see if there are resources need to be loaded
this.loadResource();
// update rcuList
this.updateRcuList();
},
/**
* get resource type by analysize url
* @param {String} url
* @return {String}
*/
getResType: function( url ){
var c = this.config, i,
scriptEx, dataEx, imgEx = scriptEx = dataEx = '\\w+\\.\(';
for( i = 0; c.scriptSuffix[ i ]; i++ ){
if( i == c.scriptSuffix.length - 1 ){
scriptEx += ( '\(' + c.scriptSuffix[ i ] + '\)\)$' );
}
else {
scriptEx += ( '\(' + c.scriptSuffix[ i ] + '\)\|' );
}
}
for( i = 0; c.dataSuffix[ i ]; i++ ){
if( i == c.dataSuffix.length - 1 ){
dataEx += ( '\(' + c.dataSuffix[ i ] + '\)\)$' );
}
else {
dataEx += ( '\(' + c.dataSuffix[ i ] + '\)\|' );
}
}
for( i = 0; c.imageSuffix[ i ]; i++ ){
if( i == c.imageSuffix.length - 1 ){
imgEx += ( '\(' + c.imageSuffix[ i ] + '\)\)$' );
}
else {
imgEx += ( '\(' + c.imageSuffix[ i ] + '\)\|' );
}
}
scriptEx = new RegExp( scriptEx );
dataEx = new RegExp( dataEx );
imgEx = new RegExp( imgEx );
if( scriptEx.test( url ) ){
return 'script';
}
else if( dataEx.test( url ) ){
return 'data';
}
else if( imgEx.test( url ) ){
return 'image';
}
//@error
else {
this.errorHandle( 'warning', 'unknown resource type: ' + url );
}
},
/**
* get rely file
* @param {String} data
* @return {Array}
* @example $r._rely ( [ 'a.js', 'b.js' ] )
* Add this to comments can achieve the same effect
*/
getRely: function( data ){
var EX = /\$r\s*\.\s*_rely\s*\(\s*\[\s*([\w\.,'"\s]+)\s*\]\s*\)/,
relyStr = EX.exec( data ), relyList;
if( !relyStr ){
return [];
}
relyStr = relyStr[ 1 ];
// Remove all the spaces and all quotes
relyStr = relyStr.replace( /['"\s]/g, '' );
relyList = relyStr.split( /,/ );
return relyList
},
/**
* add elem to loadingList
* @param {Array[Strin]}
*/
addLoadingList: function( list ){
// check if they have been loaded
for( i = 0; list[ i ]; i++ ){
if( !( list[ i ] in this.finishedList ) && !( list[ i ] in this.loadingList ) ){
this.loadingList[ list[ i ] ] = {
status: 'wait',
type: this.getResType( list[ i ] )
};
}
}
},
/**
* buildScript
* @param {Object} r -resource collection unit
* @param {Boolean} s default true
* @returns {String} if s set to true, then return the script to be execued, else return script array
*/
buildScript: function( r, s ){
var i, j, relyIndex = {}, script = [], t, urlTemp = [];
// copy url list
for( i = 0; r.url[ i ]; i++ ){
urlTemp.push( r.url[ i ] );
}
for( i = 0; r.url[ i ]; i++ ){
t = this.finishedList[ r.url[ i ] ].type;
if( t == 'script' ){
// check if this resource have been execued
if( this.scriptList[ r.url[ i ] ] && this.scriptList[ r.url[ i ] ] == 'execued' ){
// remove from url list
r.url.splice( i, 1 );
i--;
}
}
}
// Remove duplicate rely
for( i = 0; r.rely[ i ]; i++ ){
for( j = 0; r.url[ j ]; j++ ){
if( r.url[ j ] == r.rely[ i ] ){
if( !relyIndex[ r.rely[ i ] ] ){
relyIndex[ r.rely[ i ] ] = j;
}
else if( j < relyIndex[ r.rely[ i ] ] ){
r.url[ relyIndex[ r.rely[ i ] ] ] = undefined;
relyIndex[ r.rely[ i ] ] = j;
}
else if( j > relyIndex[ r.rely[ i ] ] ){
r.url[ relyIndex[ j ] ] = undefined;
}
}
}
}
// get all script resource into an array
for( i = 0; r.url[ i ]; i++ ){
t = this.finishedList[ r.url[ i ] ].type;
if( t == 'script' ){
script.push( this.finishedList[ r.url[ i ] ].data );
}
}
// build Script
return script = script.join('\n');
},
/**
* execute script
* @param {String} s
*/
runScript: function( s ){
var scr = document.createElement('script');
scr.type= "text/javascript" ;
scr.text= s;
// insert script to head
document.getElementsByTagName("head")[0].appendChild(scr);
// remove script
document.getElementsByTagName("head")[0].removeChild(scr);
this.log( 'info', 'resource [script] execued !' );
},
/**
* update rcuList
* Traverse rcuList to see if any is finished, then call the callback
* and save the module
*/
updateRcuList: function(){
var i, j, finished = true, s, a,
callback, userData;
// tranverse url list
for( i = 0; this.rcuList[ i ]; i++ ){
for( j = 0; this.rcuList[ i ].url[ j ]; j++ ){
if( !( this.rcuList[ i ].url[ j ] in this.finishedList ) ){
finished = false;
break;
}
}
if( finished ){
// save module
if( this.rcuList[ i ].alias ){
a = this.rcuList[ i ].alias;
}
else {
a = this.moduleAliasPrefix + ( ++this.moduleAliasCounter );
}
this.moduleList[ a ] = this.initModule( this.rcuList[ i ] );
// run script
this.runScript( this.buildScript( this.rcuList[ i ] ) );
// update scriptList
for( j = 0; this.rcuList[ i ].url[ j ]; j++ ){
if( this.finishedList[ this.rcuList[ i ].url[ j ] ].type == 'script' ){
this.scriptList[ this.rcuList[ i ].url[ j ] ] = 'execued';
}
}
// backup callback and userData
callback = this.rcuList[ i ].callback;
userData = this.rcuList[ i ].userData;
// remove rcu
this.rcuList.splice( i, 1 );
// callback
if( callback ){
// pass module data to callback, an set context to window
callback.call( window, this.moduleList[ a ], userData );
}
i--;
this.log( 'info', 'a rcuList finished loading !' );
}
else {
break;
}
finished = true;
}
},
/**
* init module
* @param {Object} r resource collection unit
* @return {Object}
*/
initModule: function( r ){
var m = {}, i, j;
for( i in r.url ){
m[ r.url[ i ] ] = this.finishedList[ r.url[ i ] ];
// check if the resource has an alias
for( j in this.aliasList ){
if( this.aliasList[ j ] == r.url[ i ] ){
m[ j ] = this.finishedList[ r.url[ i ] ];
break;
}
}
}
return m;
}
}
/**
* relyJS API
*/
/**
* load resource
* url: [ 'a.js', 'b.png', 'http://neekey.net/importJS.js' ] - resource url
* rely: [ 'c.js', '../d.js' ], - rely resource url
* alias: 'module', - the name of this collection, optional
* callback: fn,
* userData: , - custom data pass to callback
*/
$r.load = function( o ) {
var alias;
BASE_PATH = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
// if url not specified
if ( !o || !o.url ){
pri.errorHandle( 'warning', '[ $r.load ] illegal argument ! url must be given!' );
return this;
}
else {
// check url data type
if( typeof o.url == 'string' || o.url.constructor == Array ) {
// check rely, alias, callback
// if illegal, set to undefined
if( !o.rely || !( typeof o.rely == 'string' || o.rely.constructor == Array ) ){
o.rely = [];
}
else if( typeof o.rely == 'string' ){
o.rely = [ o.rely ];
}
if( o.alias && typeof o.alias != 'string' ){
o.alias = undefined;
}
if( o.callback && typeof o.callback != 'function' ){
o.callback = undefined;
}
if( typeof o.url == 'string' ){
o.url = [ o.url ];
}
// handle URL and store alias
for( i = 0; o.url[ i ]; i++ ){
alias = pri.getAlias( o.url[ i ] );
o.url[ i ] = util.handleUrl( o.url[ i ], BASE_PATH );
if( alias != '' ){
pri.aliasList[ alias ] = o.url[ i ];
}
}
for( i = 0; o.rely && o.rely[ i ]; i++ ){
alias = pri.getAlias( o.rely[ i ] );
o.rely[ i ] = util.handleUrl( o.rely, BASE_PATH );
if( alias != '' ){
pri.aliasList[ alias ] = o.rely[ i ];
}
}
// initialize resource collection unit
pri.initRcu( o );
pri.loadResource();
// update rcuList
pri.updateRcuList();
return this;
}
else {
pri.errorHandle( 'warning', '[ $r.load ] illegal argument ! the data type of url must be String or Array!' );
return this;
}
}
};
/**
* specify files the resource need rely on
*/
$r.rely = function( rely ) {
// check data type
if( rely.constructor == Array ){
var r = pri.rcuList[ pri.rcuList.length - 1 ];
// insert to the top of r.url
r.url = rely.concat( r.url );
r.rely = rely.concat( r.rely );
// add url to loadingList
pri.addLoadingList( r.url );
pri.loadResource();
// update rcuList
pri.updateRcuList();
}
else {
this.errorHandle( 'warning', '[ $r.rely ] illegal argument ! the data type of rely must be Array!' );
}
return this;
};
/**
* configuration
*/
$r.config = function( cfg ) {
var i;
for( i in cfg ){
if( i == 'scriptSuffix' || i == 'dataSuffix' || i == 'imageSuffix' || i == 'log' ){
pri.config[ i ] = cfg[ i ];
}
}
return this;
};
/**
* get resource by url | module name
*/
$r.getRes = function( name ) {
var URL_EX = /^http\:\/\/.+$|^https\:\/\/.+$/;
if( !name ){
return ;
}
// if name is an absolute url
else if ( name in pri.finishedList ) {
return pri.finishedList[ name ];
}
// or it's an alias
else if ( name in pri.aliasList ){
return pri.finishedList[ pri.aliasList[ name ] ];
}
else return false;
};
/**
* get module
*/
$r.getModule = function( name ){
if( name && name in pri.moduleList ){
return pri.moduleList[ name ];
}
else return false;
};
/**
* this function does nothing,
* just a Identifier for you to import other resource in a resource
* @param {Array}
*/
$r._rely = function(){};
/**
* return the logList
*/
$r.log = function(){
return pri.logList;
}
})();