OnChunksLoadedRuntimeModule.js 2.0 KB

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