loader.ejs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. let registry = {};
  16. // Used for `eval` and `importScripts` where we can't get script URL by other means.
  17. // In both cases, it's safe to use a global var because those functions are synchronous.
  18. let nextDefineUri;
  19. const singleRequire = (uri, parentUri) => {
  20. uri = new URL(uri + ".js", parentUri).href;
  21. return registry[uri] || (
  22. <% if (useEval) { %>
  23. fetch(uri)
  24. .then(resp => resp.text())
  25. .then(code => {
  26. nextDefineUri = uri;
  27. eval(code);
  28. })
  29. <% } else { %>
  30. new Promise(resolve => {
  31. if ("document" in self) {
  32. const script = document.createElement("script");
  33. script.src = uri;
  34. script.onload = resolve;
  35. document.head.appendChild(script);
  36. } else {
  37. nextDefineUri = uri;
  38. importScripts(uri);
  39. resolve();
  40. }
  41. })
  42. <% } %>
  43. .then(() => {
  44. let promise = registry[uri];
  45. if (!promise) {
  46. throw new Error(`Module ${uri} didn’t register its module`);
  47. }
  48. return promise;
  49. })
  50. );
  51. };
  52. self.<%- amdFunctionName %> = (depsNames, factory) => {
  53. const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href;
  54. if (registry[uri]) {
  55. // Module is already loading or loaded.
  56. return;
  57. }
  58. let exports = {};
  59. const require = depUri => singleRequire(depUri, uri);
  60. const specialDeps = {
  61. module: { uri },
  62. exports,
  63. require
  64. };
  65. registry[uri] = Promise.all(depsNames.map(
  66. depName => specialDeps[depName] || require(depName)
  67. )).then(deps => {
  68. factory(...deps);
  69. return exports;
  70. });
  71. };
  72. }