forked from nikhilk/scriptsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.js
More file actions
492 lines (441 loc) · 16.6 KB
/
Copy pathloader.js
File metadata and controls
492 lines (441 loc) · 16.6 KB
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
(function () {
var _head = document.getElementsByTagName('head')[0];
var _downloaderType = navigator.userAgent.indexOf('MSIE') > 0 ? 'img' : 'object';
var _xdomainRegex = /^https?:\/\/.*/;
// Storage cookie defaults to 'scripts', but can be overriden via a scriptCookie
// expando on the document.
var _storageCookie = document.scriptCookie || 'scripts';
// Debuggable scripts defaults to false, but can be overriden via a scriptDebugging
// flag set to true on the document object.
var _debuggableScripts = document.scriptDebugging || false;
// The script loader provides functionality to download scripts from the network
// and load/save from/to local storage. A script loader can be specified on the
// document, and if not a default implementation if used here.
var _scriptLoader = document.scriptLoader ||
{
download: function (script, callback) {
// Use the x-domain loader if the script is x-domain, or we're
// in debug mode (when using the x-domain loader, we end up
// inserting an actual script element to subsequently load the script
// into the page, enabling debugging)
if (_debuggableScripts || _xdomainRegex.test(script.src)) {
// Downloads script using an img tag (in IE) or an object tag (in other
// browsers).
var downloader = document.createElement(_downloaderType);
downloader.style.width = downloader.style.height = '0px';
downloader.onload = downloader.onerror = function () {
downloader.onload = downloader.onerror = null;
callback();
};
downloader.src = downloader.data = script.src;
document.body.appendChild(downloader);
}
else {
// Downloads script using an XHR object. This allows us to retrieve the
// content of the script and thereby allow us to subsequently use the
// script text to insert a script element into the page, when the time
// comes to load the script.
var downloader = new XMLHttpRequest();
downloader.onreadystatechange = function () {
if (downloader.readyState == 4) {
downloader.onreadystatechange = null;
script.useText = true;
script.text = downloader.responseText;
callback();
}
};
downloader.open('GET', script.src, true);
downloader.send();
}
},
canStore: !!window.localStorage,
load: function (name) {
return window.localStorage['script.' + name];
},
save: function (name, version, text) {
window.localStorage['script.' + name] = text;
// Save the fact that we have stored this script into the local storage
// by updating the index with the new script information, and using
// the index as the value of the cookie sent to the server as well.
var scriptIndex = window.localStorage['script.$'];
scriptIndex = scriptIndex ? JSON.parse(scriptIndex) : {};
scriptIndex[name] = version;
scriptIndex = JSON.stringify(scriptIndex);
window.localStorage['script.$'] = scriptIndex;
// A cookie with 180 days = 60 * 60 * 24 * 180 seconds
document.cookie = _storageCookie + '=' + encodeURIComponent(scriptIndex) +
'; max-age=15552000; path=/';
}
};
var _initCallbacks = [];
var _readyCallbacks = [];
var _registeredScripts = {};
var _started = false;
// Checks if the specified required scripts have been loaded.
function checkScripts(name, requiredNames) {
if (requiredNames) {
requiredNames.split(',').forEach(function (s) {
if (!_registeredScripts[s] || !_registeredScripts[s].loaded) {
console.error(s + ' has not been loaded before ' + name);
}
});
}
}
// Loads the specified script or scripts (identified by their registered
// names) and invokes the specified callback (along with optional context)
// when the scripts have been loaded.
function loadScripts(scriptNames, callback, context) {
scriptNames = scriptNames['push'] ? scriptNames : [scriptNames];
_loadScripts(scriptNames, callback, context);
}
// Registers a callback to be invoked before script initialization occurs.
// This is raised in response to the DOMContentLoaded event.
// If initialization is complete, the callback is immediately invoked.
function registerInitCallback(callback) {
_initCallbacks ? _initCallbacks.push(callback) : setTimeout(callback, 0);
}
// Registers a callback to be invoked once startup scripts have been loaded
// into the page, and any inline scripts have been executed.
// If the page is ready, the callback is immediately invoked.
function registerReadyCallback(callback) {
_readyCallbacks ? _readyCallbacks.push(callback) : setTimeout(callback, 0);
}
// Registers a script programmatically. A script object has the following
// structure:
// {
// name: <name of script>,
// src: <url of script>,
// requires: <optional array of script dependencies>
// }
function registerScript(script) {
script.loaded = false;
_registeredScripts[script.name] = script;
}
// Downloads the script into the browser's cache, and invokes the specified
// callback (optional) upon completion. The script is not loaded into the page,
// i.e. it is not executed just yet.
function _downloadScript(script, callback) {
if (script.downloaded) {
// Already downloaded, so invoke the callback immediately.
if (callback) {
callback(script);
}
return;
}
if (script.store && _scriptLoader.canStore) {
if (script.store == 'load') {
// Load the script content from local storage using the script name
// as a key into local storage.
script.useText = true;
script.text = _scriptLoader.load(script.name);
}
else {
// Save the inline script content using specified version into local
// storage, using the name as a key. The value of data-store on the
// script element is interpreted as the version identifier.
script.useText = true;
_scriptLoader.save(script.name, script.store, script.text);
}
script.downloaded = true;
if (callback) {
callback(script);
}
return;
}
if (script.downloading) {
// The script is already being downloaded, so just tack on the
// callback to the script element.
if (callback) {
if (!script.downloadCallbacks) {
script.downloadCallbacks = [callback];
}
else {
script.downloadCallbacks.push(callback);
}
}
return;
}
script.downloading = true;
var cb = function () {
script.downloaded = true;
script.downloading = false;
if (callback) {
callback(script);
}
if (script.downloadCallbacks) {
script.downloadCallbacks.forEach(function (cb) {
cb(script);
});
delete script.downloadCallbacks;
}
};
_scriptLoader.download(script, cb);
}
// Loads the script into the page, by inserting an actual script element,
// and invoking the specified callback once the script has been loaded.
function _execScript(script, callback) {
if (script.loaded) {
// Already loaded. Invoke the callback immediately.
callback(script);
return;
}
var s = document.createElement('script');
s.type = 'text/javascript';
if (script.useText) {
// Load the script with script content inline. This allows us to load script
// while making sure another download is not incurred.
s.text = script.text;
setTimeout(function () {
script.loaded = true;
callback(script);
}, 0);
}
else {
// Load the script with its src. This ensures the script is debuggable, i.e. listed
// within the browser's loaded scripts.
s.onload = s.onreadystatechange = function () {
if (s.readyState && s.readyState != 'complete' && s.readyState != 'loaded') {
return;
}
s.onload = s.onreadystatechange = null;
script.loaded = true;
callback(script);
};
s.src = script.src;
}
_head.appendChild(s);
}
// Loads script with script content inline.
function _evalScript(script) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.text = script.text;
_head.appendChild(s);
}
// Helper to invoke a set of callbacks.
function _invokeCallbacks(callbacks) {
if (callbacks && callbacks.length) {
callbacks.forEach(function (callback) {
callback();
});
}
}
// Loads a set of scripts and invokes the specified callback along
// with specified context.
function _loadScripts(scriptNames, callback, context) {
if (scriptNames.length == 0) {
callback(context);
return;
}
var loadCount = 0;
var downloaded = [];
// This is invoked everytime a script has been loaded/executed within the page.
function scriptLoaded(script) {
loadCount++;
if (scriptNames.length == loadCount) {
// All scripts have been loaded, so now invoke the passed in callback.
callback(context);
}
else {
if (downloaded.length) {
// Try to process any downloads that need to be downloaded, as this
// script might have been the dependency of one of those pending scripts.
processDownloaded();
}
}
}
// This is invoked everytime a script has been downloaded. We add it to the list
// of downloaded scripts and attempt to process it further.
function scriptDownloaded(script) {
downloaded.push(script);
processDownloaded();
}
// This processes a set of downloaded scripts. Any scripts whose dependencies
// have also been loaded will be executed.
function processDownloaded() {
// Hold on to the list of downloaded scripts needing to be processed
// in this iteration.
var scripts = downloaded;
if (scripts.length) {
// Reset the downloaded scripts array, so scripts can be added to it
// for being processed in a subsequent iteration.
downloaded = [];
scripts.forEach(function (script) {
var load = true;
if (script.requires) {
// Check if all dependencies have been loaded to determine if this
// script should now be loaded into the page.
load = script.requires.every(function (dependencyName) {
return _registeredScripts[dependencyName].loaded;
});
}
if (load) {
_execScript(script, scriptLoaded);
}
else {
// A dependency has not yet been loaded, so re-add it to
// the list of downloads. The list of downloads will be
// re-examined when another script is downloaded or loaded
// into the page.
downloaded.push(script);
}
});
}
}
// Expand the list of script names to include any dependencies not
// already included in the list that haven't already been loaded.
var scriptMap = {};
scriptNames.forEach(function (name) {
scriptMap[name] = name;
});
var i = 0;
do {
var script = _registeredScripts[scriptNames[i++]];
if (script.requires) {
for (var j = script.requires.length - 1; j >= 0; j--) {
var dependencyName = script.requires[j];
if (!scriptMap[dependencyName] && !_registeredScripts[dependencyName].loaded) {
// Found a dependency that needs to be included into the list
// of scripts to be loaded, since it is a required dependency.
scriptNames.push(dependencyName);
scriptMap[dependencyName] = dependencyName;
}
}
}
} while (i < scriptNames.length);
// Kick off downloading any scripts that need to be downloaded.
// For those scripts that have been loaded, we don't need to attempt
// downloading/loading them, but we do need to track them, so we know when
// all required scripts have been loaded so as to invoke the passed in
// callback.
var done = true;
scriptNames.forEach(function (name) {
var script = _registeredScripts[name];
if (script.loaded) {
loadCount++;
}
else {
_downloadScript(script, scriptDownloaded);
done = false;
}
});
// If we're done, i.e. all scripts were already loaded, then just go ahead
// and invoke the passed in callback.
if (done) {
callback(context);
}
}
// Invoke any ready callbacks that have been registered.
function _raiseReady(deferredScripts) {
// Kick off downloads for any deferred scripts (but don't load them into the
// page just yet).
deferredScripts.forEach(function (name) {
var script = _registeredScripts[name];
if (script.loaded) {
return;
}
_downloadScript(script);
});
var readyCallbacks = _readyCallbacks;
_readyCallbacks = null;
_invokeCallbacks(readyCallbacks);
}
// Perform the page startup logic (in response to the DOMContentLoaded
// notification raised by the DOM document, or an explicit call to load).
function _startup() {
if (_started) {
return;
}
_started = true;
// First invoke the registered init callbacks. This allows page code
// to programmatically register scripts.
var initCallbacks = _initCallbacks;
_initCallbacks = null;
_invokeCallbacks(initCallbacks);
// Storage cookie defaults to 'scripts', but can be overriden via an
// attribute on the body element.
_storageCookie = document.body.getAttribute('data-scripts-cookie') || 'scripts';
var startupScripts = [];
var deferredScripts = [];
var inlineScripts = [];
// Extract the list of registered scripts and inline scripts by enumerating
// script elements with type = text/script.
var scriptElements = document.getElementsByTagName('script');
for (var i = 0, count = scriptElements.length; i < count; i++) {
var scriptElement = scriptElements[i];
if (scriptElement.type == 'text/script') {
var script = {
name: scriptElement.getAttribute('data-name'),
src: scriptElement.getAttribute('data-src'),
requires: scriptElement.getAttribute('data-requires'),
mode: scriptElement.getAttribute('data-mode') || 'startup',
text: scriptElement.text,
store: scriptElement.getAttribute('data-store')
};
if (script.requires) {
script.requires = script.requires.split(',');
}
if (script.name) {
registerScript(script);
if (script.mode == 'startup') {
startupScripts.push(script.name);
}
else if (script.mode == 'deferred') {
deferredScripts.push(script.name);
}
// TODO: Error check - script.mode must be 'ondemand'
}
else {
inlineScripts.push(script);
}
}
}
// Load the startup scripts, and once that is done, execute any inline
// scripts there are on the page.
_loadScripts(startupScripts, function () {
var inlinesProcessed = 0;
if (inlineScripts.length) {
inlineScripts.forEach(function (script) {
if (script.requires) {
// If an inline script has a dependency on other scripts, ensure
// they are loaded first.
_loadScripts(script.requires, function (s) {
_evalScript(s);
inlinesProcessed++;
// If all the inlines have been processed, then go ahead and invoke
// the ready callbacks.
if (inlinesProcessed == inlineScripts.length) {
_raiseReady(deferredScripts);
}
}, script);
}
else {
_evalScript(script);
inlinesProcessed++;
}
});
}
// If all the inlines have been processed, then go ahead and invoke
// the ready callbacks.
if (inlinesProcessed == inlineScripts.length) {
_raiseReady(deferredScripts);
}
});
}
window.loader = {
load: _startup,
loadScripts: loadScripts,
checkScripts: checkScripts,
registerScript: registerScript,
init: registerInitCallback,
ready: registerReadyCallback
};
if (document.addEventListener) {
document.readyState == 'complete' ? _startup() : document.addEventListener('DOMContentLoaded', _startup, false);
}
else if (window.attachEvent) {
window.attachEvent('onload', function () {
_startup();
});
}
})();