123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- var pendingClasses = [];
- var loadedClasses = [];
- var cacheBusting = true;
- var autoloader = (classname) => {
- if (pendingClasses.indexOf(classname) != -1) {
- return Promise.resolve();
- }
- pendingClasses.push(classname);
- return new Promise((resolve, reject) => {
- if (loadedClasses.indexOf(classname) != -1) {
- pendingClasses.splice(pendingClasses.indexOf(classname), 1);
- resolve(window[classname]);
- return;
- }
- let url = `./js/${classname}.js`;
- if (cacheBusting) {
- url += "?v=" + new Date().getTime();
- }
- 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);
- }
- });
|