autoload.js 1.4 KB

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