/**
* A script library to import the javascript / css file on the fly
*
* @author Aby Dahana <abydahana@gmail.com>
* @copyright (c) Aksara Laboratory <https://aksaracms.com>
* @license MIT License
*
* This source file is subject to the MIT license that is bundled with this
* source code in the LICENSE.txt file.
*/
"use strict";
let loaded_sources = [];
const require = (function() {
return {
js: async function(sources, callback) {
if (typeof $ === 'undefined') {
console.log('jQuery is required to use require.js()');
return;
}
if (! $.isArray(sources)) {
sources = [sources];
}
let deferred = new $.Deferred(),
pipe = deferred;
sources.forEach(async function(source, index) {
if ($.inArray(source, loaded_sources) === -1) {
loaded_sources.push(source);
pipe = pipe.then(async function() {
if ((index + 1) === sources.length) {
await $.getScript(source, function() {
deferred.resolve();
if (typeof callback === 'function') {
return callback();
}
});
} else {
return await $.getScript(source);
}
});
} else if ((index + 1) === sources.length && typeof callback === 'function') {
return callback();
}
});
deferred.resolve();
},
css: async function(sources, callback) {
if (typeof $ === 'undefined') {
console.log('jQuery is required to use require.css()');
return;
}
if (! $.isArray(sources)) {
sources = [sources];
}
sources.forEach(async function(source, index) {
if ($.inArray(source, loaded_sources) === -1) {
loaded_sources.push(source);
$('<link rel="stylesheet" type="text/css" href="' + source + '" />').appendTo('head');
if ((index + 1) === sources.length && typeof callback === 'function') {
await callback.call();
}
} else {
if ((index + 1) === sources.length && typeof callback === 'function') {
await callback.call();
}
}
});
}
}
})();
|