LoadScriptRuntimeModule.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const { SyncWaterfallHook } = require("tapable");
  6. const Compilation = require("../Compilation");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. const HelperRuntimeModule = require("./HelperRuntimeModule");
  10. /** @typedef {import("../Chunk")} Chunk */
  11. /** @typedef {import("../Compiler")} Compiler */
  12. /**
  13. * @typedef {Object} LoadScriptCompilationHooks
  14. * @property {SyncWaterfallHook<[string, Chunk]>} createScript
  15. */
  16. /** @type {WeakMap<Compilation, LoadScriptCompilationHooks>} */
  17. const compilationHooksMap = new WeakMap();
  18. class LoadScriptRuntimeModule extends HelperRuntimeModule {
  19. /**
  20. * @param {Compilation} compilation the compilation
  21. * @returns {LoadScriptCompilationHooks} hooks
  22. */
  23. static getCompilationHooks(compilation) {
  24. if (!(compilation instanceof Compilation)) {
  25. throw new TypeError(
  26. "The 'compilation' argument must be an instance of Compilation"
  27. );
  28. }
  29. let hooks = compilationHooksMap.get(compilation);
  30. if (hooks === undefined) {
  31. hooks = {
  32. createScript: new SyncWaterfallHook(["source", "chunk"])
  33. };
  34. compilationHooksMap.set(compilation, hooks);
  35. }
  36. return hooks;
  37. }
  38. /**
  39. * @param {boolean=} withCreateScriptUrl use create script url for trusted types
  40. */
  41. constructor(withCreateScriptUrl) {
  42. super("load script");
  43. this._withCreateScriptUrl = withCreateScriptUrl;
  44. }
  45. /**
  46. * @returns {string} runtime code
  47. */
  48. generate() {
  49. const { compilation } = this;
  50. const { runtimeTemplate, outputOptions } = compilation;
  51. const {
  52. scriptType,
  53. chunkLoadTimeout: loadTimeout,
  54. crossOriginLoading,
  55. uniqueName,
  56. charset
  57. } = outputOptions;
  58. const fn = RuntimeGlobals.loadScript;
  59. const { createScript } =
  60. LoadScriptRuntimeModule.getCompilationHooks(compilation);
  61. const code = Template.asString([
  62. "script = document.createElement('script');",
  63. scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "",
  64. charset ? "script.charset = 'utf-8';" : "",
  65. `script.timeout = ${loadTimeout / 1000};`,
  66. `if (${RuntimeGlobals.scriptNonce}) {`,
  67. Template.indent(
  68. `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  69. ),
  70. "}",
  71. uniqueName
  72. ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);'
  73. : "",
  74. `script.src = ${
  75. this._withCreateScriptUrl
  76. ? `${RuntimeGlobals.createScriptUrl}(url)`
  77. : "url"
  78. };`,
  79. crossOriginLoading
  80. ? Template.asString([
  81. "if (script.src.indexOf(window.location.origin + '/') !== 0) {",
  82. Template.indent(
  83. `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
  84. ),
  85. "}"
  86. ])
  87. : ""
  88. ]);
  89. return Template.asString([
  90. "var inProgress = {};",
  91. uniqueName
  92. ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};`
  93. : "// data-webpack is not used as build has no uniqueName",
  94. "// loadScript function to load a script via script tag",
  95. `${fn} = ${runtimeTemplate.basicFunction("url, done, key, chunkId", [
  96. "if(inProgress[url]) { inProgress[url].push(done); return; }",
  97. "var script, needAttach;",
  98. "if(key !== undefined) {",
  99. Template.indent([
  100. 'var scripts = document.getElementsByTagName("script");',
  101. "for(var i = 0; i < scripts.length; i++) {",
  102. Template.indent([
  103. "var s = scripts[i];",
  104. `if(s.getAttribute("src") == url${
  105. uniqueName
  106. ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key'
  107. : ""
  108. }) { script = s; break; }`
  109. ]),
  110. "}"
  111. ]),
  112. "}",
  113. "if(!script) {",
  114. Template.indent([
  115. "needAttach = true;",
  116. createScript.call(code, this.chunk)
  117. ]),
  118. "}",
  119. "inProgress[url] = [done];",
  120. "var onScriptComplete = " +
  121. runtimeTemplate.basicFunction(
  122. "prev, event",
  123. Template.asString([
  124. "// avoid mem leaks in IE.",
  125. "script.onerror = script.onload = null;",
  126. "clearTimeout(timeout);",
  127. "var doneFns = inProgress[url];",
  128. "delete inProgress[url];",
  129. "script.parentNode && script.parentNode.removeChild(script);",
  130. `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction(
  131. "fn(event)",
  132. "fn"
  133. )});`,
  134. "if(prev) return prev(event);"
  135. ])
  136. ),
  137. ";",
  138. `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`,
  139. "script.onerror = onScriptComplete.bind(null, script.onerror);",
  140. "script.onload = onScriptComplete.bind(null, script.onload);",
  141. "needAttach && document.head.appendChild(script);"
  142. ])};`
  143. ]);
  144. }
  145. }
  146. module.exports = LoadScriptRuntimeModule;