OnChunksLoadedRuntimeModule.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * @returns {string | null} runtime code
  15. */
  16. generate() {
  17. const compilation = /** @type {Compilation} */ (this.compilation);
  18. const { runtimeTemplate } = compilation;
  19. return Template.asString([
  20. "var deferred = [];",
  21. `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction(
  22. "result, chunkIds, fn, priority",
  23. [
  24. "if(chunkIds) {",
  25. Template.indent([
  26. "priority = priority || 0;",
  27. "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];",
  28. "deferred[i] = [chunkIds, fn, priority];",
  29. "return;"
  30. ]),
  31. "}",
  32. "var notFulfilled = Infinity;",
  33. "for (var i = 0; i < deferred.length; i++) {",
  34. Template.indent([
  35. runtimeTemplate.destructureArray(
  36. ["chunkIds", "fn", "priority"],
  37. "deferred[i]"
  38. ),
  39. "var fulfilled = true;",
  40. "for (var j = 0; j < chunkIds.length; j++) {",
  41. Template.indent([
  42. `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${
  43. RuntimeGlobals.onChunksLoaded
  44. }).every(${runtimeTemplate.returningFunction(
  45. `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`,
  46. "key"
  47. )})) {`,
  48. Template.indent(["chunkIds.splice(j--, 1);"]),
  49. "} else {",
  50. Template.indent([
  51. "fulfilled = false;",
  52. "if(priority < notFulfilled) notFulfilled = priority;"
  53. ]),
  54. "}"
  55. ]),
  56. "}",
  57. "if(fulfilled) {",
  58. Template.indent([
  59. "deferred.splice(i--, 1)",
  60. "var r = fn();",
  61. "if (r !== undefined) result = r;"
  62. ]),
  63. "}"
  64. ]),
  65. "}",
  66. "return result;"
  67. ]
  68. )};`
  69. ]);
  70. }
  71. }
  72. module.exports = OnChunksLoadedRuntimeModule;