oxjs/source/Ox.js

90 lines
2.6 KiB
JavaScript
Raw Normal View History

// Ox.js Developer Version
2011-04-27 19:39:56 +00:00
/*
Usage:
Ox.load(callback)
Ox.load(module, callback)
Ox.load(module, options, callback)
Ox.load({module: options, module: options}, callback)
*/
2011-04-27 19:39:56 +00:00
Ox = {
2011-04-27 19:39:56 +00:00
load: function() {
var args = arguments,
callback = args[args.length - 1],
path = getPath();
2011-04-27 19:39:56 +00:00
loadJSON(function(data) {
loadScripts(data, function() {
if (args.length == 1) {
callback()
} else {
Ox.load.apply(null, args);
}
2011-04-27 19:39:56 +00:00
});
});
function getPath() {
var i, scripts = document.getElementsByTagName('script');
for (i = 0; i < scripts.length; i++) {
if (/Ox\.js$/.test(scripts[i].src)) {
return scripts[i].src.replace(/Ox\.js$/, '');
2011-04-27 19:39:56 +00:00
}
}
2011-04-27 19:39:56 +00:00
}
2011-05-06 23:30:32 +00:00
function loadJSON(callback) {
var req = new XMLHttpRequest();
req.open('GET', path + 'Ox/json/Ox.json', true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
callback(JSON.parse(req.responseText));
} else {
// ...
}
}
};
req.send();
2011-09-20 00:11:16 +00:00
}
function loadScripts(scripts, callback) {
loadScriptsOrdered(scripts[0], function() {
loadScriptsUnordered(scripts[1], function() {
loadScriptsUnordered(scripts[2], callback);
2011-09-17 13:05:16 +00:00
});
});
2011-09-17 13:05:16 +00:00
}
function loadScriptsOrdered(scripts, callback) {
loadScript(scripts.shift(), function() {
if (scripts.length) {
loadScriptsOrdered(scripts, callback);
} else {
callback();
}
});
}
function loadScriptsUnordered(scripts, callback) {
var counter = 0, i, length = scripts.length;
for (i = 0; i < length; i++) {
loadScript(scripts[i], function() {
++counter == length && callback();
});
}
2011-04-27 19:39:56 +00:00
}
function loadScript(script, callback) {
var element = document.createElement('script');
element.onload = callback;
2011-10-08 17:19:18 +00:00
element.src = path + script + '?' + parseInt(Math.random() * 1000000);
element.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(element);
2011-04-27 19:39:56 +00:00
}
}
2011-04-27 19:39:56 +00:00
};