loader.ejs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Copyright 2018 Google Inc. All Rights Reserved.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. * Unless required by applicable law or agreed to in writing, software
  8. * distributed under the License is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. * See the License for the specific language governing permissions and
  11. * limitations under the License.
  12. */
  13. // If the loader is already loaded, just stop.
  14. if (!self.<%- amdFunctionName %>) {
  15. const singleRequire = name => {
  16. if (name !== 'require') {
  17. name = name + '.js';
  18. }
  19. let promise = Promise.resolve();
  20. if (!registry[name]) {
  21. <% if (useEval) { %>
  22. promise = fetch(name)
  23. .then(resp => resp.text())
  24. .then(code => eval(code));
  25. <% } else { %>
  26. promise = new Promise(async resolve => {
  27. if ("document" in self) {
  28. const script = document.createElement("script");
  29. script.src = name;
  30. document.head.appendChild(script);
  31. script.onload = resolve;
  32. } else {
  33. importScripts(name);
  34. resolve();
  35. }
  36. });
  37. <% } %>
  38. }
  39. return promise.then(() => {
  40. if (!registry[name]) {
  41. throw new Error(`Module ${name} didn’t register its module`);
  42. }
  43. return registry[name];
  44. });
  45. };
  46. const require = (names, resolve) => {
  47. Promise.all(names.map(singleRequire))
  48. .then(modules => resolve(modules.length === 1 ? modules[0] : modules));
  49. };
  50. const registry = {
  51. require: Promise.resolve(require)
  52. };
  53. self.<%- amdFunctionName %> = (moduleName, depsNames, factory) => {
  54. if (registry[moduleName]) {
  55. // Module is already loading or loaded.
  56. return;
  57. }
  58. registry[moduleName] = Promise.resolve().then(() => {
  59. let exports = {};
  60. const module = {
  61. uri: location.origin + moduleName.slice(1)
  62. };
  63. return Promise.all(
  64. depsNames.map(depName => {
  65. switch(depName) {
  66. case "exports":
  67. return exports;
  68. case "module":
  69. return module;
  70. default:
  71. return singleRequire(depName);
  72. }
  73. })
  74. ).then(deps => {
  75. const facValue = factory(...deps);
  76. if(!exports.default) {
  77. exports.default = facValue;
  78. }
  79. return exports;
  80. });
  81. });
  82. };
  83. }