OnChunksLoadedRuntimeModule.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const RuntimeModule = require("../RuntimeModule");
  7. const Template = require("../Template");
  8. /** @typedef {import("../Compilation")} Compilation */
  9. class OnChunksLoadedRuntimeModule extends RuntimeModule {
  10. constructor() {
  11. super("chunk loaded");
  12. }
  13. /**
  14. * Generates runtime code for this runtime module.
  15. * @returns {string | null} runtime code
  16. */
  17. generate() {
  18. const compilation = /** @type {Compilation} */ (this.compilation);
  19. const { runtimeTemplate } = compilation;
  20. return Template.asString([
  21. "var deferred = [];",
  22. `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction(
  23. "result, chunkIds, fn, priority",
  24. [
  25. "if(chunkIds) {",
  26. Template.indent([
  27. "priority = priority || 0;",
  28. "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];",
  29. "deferred[i] = [chunkIds, fn, priority];",
  30. "return;"
  31. ]),
  32. "}",
  33. "var notFulfilled = Infinity;",
  34. "for (var i = 0; i < deferred.length; i++) {",
  35. Template.indent([
  36. runtimeTemplate.destructureArray(
  37. ["chunkIds", "fn", "priority"],
  38. "deferred[i]"
  39. ),
  40. "var fulfilled = true;",
  41. "for (var j = 0; j < chunkIds.length; j++) {",
  42. Template.indent([
  43. `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${
  44. RuntimeGlobals.onChunksLoaded
  45. }).every(${runtimeTemplate.returningFunction(
  46. `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`,
  47. "key"
  48. )})) {`,
  49. Template.indent(["chunkIds.splice(j--, 1);"]),
  50. "} else {",
  51. Template.indent([
  52. "fulfilled = false;",
  53. "if(priority < notFulfilled) notFulfilled = priority;"
  54. ]),
  55. "}"
  56. ]),
  57. "}",
  58. "if(fulfilled) {",
  59. Template.indent([
  60. "deferred.splice(i--, 1)",
  61. "var r = fn();",
  62. "if (r !== undefined) result = r;"
  63. ]),
  64. "}"
  65. ]),
  66. "}",
  67. "return result;"
  68. ]
  69. )};`
  70. ]);
  71. }
  72. }
  73. module.exports = OnChunksLoadedRuntimeModule;