TemplateLoader.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. class TemplateLoader {
  2. constructor() {
  3. this.cacheBusting = true;
  4. TemplateLoader.TemplateCache = {};
  5. }
  6. async get(templateName) {
  7. if(!TemplateLoader.TemplateCache[templateName]) {
  8. try {
  9. TemplateLoader.TemplateCache[templateName] = await this.forceGet(templateName);
  10. } catch(e) {
  11. console.error(`Template ${templateName} not found`);
  12. return "";
  13. }
  14. }
  15. return TemplateLoader.TemplateCache[templateName];
  16. }
  17. async forceGet(templateName) {
  18. let url = `./templates/${templateName}.html`;
  19. if (this.cacheBusting) {
  20. url += "?v=" + new Date().getTime();
  21. }
  22. return await this.ajaxGet(url, { "Content-Type": 'text/html' });
  23. }
  24. ajaxGet(url, headers) {
  25. return new Promise((resolve, reject) => {
  26. var request = new XMLHttpRequest();
  27. request.open("GET", url, true);
  28. request.onreadystatechange = response => {
  29. if (request.readyState == 4) {
  30. if (request.status == 200) {
  31. resolve(request.responseText);
  32. } else {
  33. reject("finished with error", request.status);
  34. }
  35. }
  36. };
  37. request.onabort = response => {
  38. reject("abort");
  39. };
  40. request.onerror = response => {
  41. reject("error");
  42. };
  43. request.ontimeout = response => {
  44. reject("timeout");
  45. };
  46. for (let key in headers) {
  47. request.setRequestHeader(key, headers[key]);
  48. }
  49. request.send();
  50. });
  51. }
  52. }
  53. TemplateLoader.TemplateCache = {};