autoload.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var pendingClasses = [];
  2. var loadedClasses = [];
  3. var autoloader = (classname) => {
  4. pendingClasses.push(classname);
  5. return new Promise((resolve, reject) => {
  6. if(loadedClasses.indexOf(classname) != -1) {
  7. pendingClasses.splice(pendingClasses.indexOf(classname), 1);
  8. resolve(window[classname]);
  9. }
  10. let url = `./js/${classname}.js`;
  11. let script = document.createElement("script");
  12. script.src = url;
  13. script.type = "text/javascript";
  14. script.async = true;
  15. script.addEventListener('load', (event) => {
  16. pendingClasses.splice(pendingClasses.indexOf(classname), 1);
  17. loadedClasses.push(classname);
  18. resolve();
  19. });
  20. script.addEventListener('error', () => {
  21. reject(new Error(`Unable to load ${classname}: attempted location ${url}`));
  22. });
  23. document.getElementsByTagName("body")[0].appendChild(script);
  24. });
  25. };
  26. var require = (classname) => {
  27. autoloader(classname).then((classname) => {
  28. let event = new CustomEvent("JSScriptLoaded", {classname: classname});
  29. document.dispatchEvent(event);
  30. }).catch((e) => {
  31. console.error(e);
  32. });
  33. };
  34. document.addEventListener("JSScriptLoaded", (event) => {
  35. if(pendingClasses.length <= 0) {
  36. let event = new CustomEvent("JSContentLoaded", {classes: loadedClasses});
  37. document.dispatchEvent(event);
  38. }
  39. });