123456789101112131415161718192021222324252627282930313233343536373839404142 |
- var pendingClasses = [];
- var loadedClasses = [];
- var autoloader = (classname) => {
- pendingClasses.push(classname);
- return new Promise((resolve, reject) => {
- if(loadedClasses.indexOf(classname) != -1) {
- pendingClasses.splice(pendingClasses.indexOf(classname), 1);
- resolve(window[classname]);
- }
-
- let url = `./js/${classname}.js`;
- let script = document.createElement("script");
- script.src = url;
- script.type = "text/javascript";
- script.async = true;
- script.addEventListener('load', (event) => {
- pendingClasses.splice(pendingClasses.indexOf(classname), 1);
- loadedClasses.push(classname);
- resolve();
- });
- script.addEventListener('error', () => {
- reject(new Error(`Unable to load ${classname}: attempted location ${url}`));
- });
- document.getElementsByTagName("body")[0].appendChild(script);
- });
- };
- var require = (classname) => {
- autoloader(classname).then((classname) => {
- let event = new CustomEvent("JSScriptLoaded", {classname: classname});
- document.dispatchEvent(event);
- }).catch((e) => {
- console.error(e);
- });
- };
- document.addEventListener("JSScriptLoaded", (event) => {
- if(pendingClasses.length <= 0) {
- let event = new CustomEvent("JSContentLoaded", {classes: loadedClasses});
- document.dispatchEvent(event);
- }
- });
|