autoload.js 1.4 KB

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