LoadScriptRuntimeModule.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. * @param {boolean=} withFetchPriority use `fetchPriority` attribute
  41. */
  42. constructor(withCreateScriptUrl, withFetchPriority) {
  43. super("load script");
  44. this._withCreateScriptUrl = withCreateScriptUrl;
  45. this._withFetchPriority = withFetchPriority;
  46. }
  47. /**
  48. * @returns {string | null} runtime code
  49. */
  50. generate() {
  51. const compilation = /** @type {Compilation} */ (this.compilation);
  52. const { runtimeTemplate, outputOptions } = compilation;
  53. const {
  54. scriptType,
  55. chunkLoadTimeout: loadTimeout,
  56. crossOriginLoading,
  57. uniqueName,
  58. charset
  59. } = outputOptions;
  60. const fn = RuntimeGlobals.loadScript;
  61. const { createScript } =
  62. LoadScriptRuntimeModule.getCompilationHooks(compilation);
  63. const code = Template.asString([
  64. "script = document.createElement('script');",
  65. scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "",
  66. charset ? "script.charset = 'utf-8';" : "",
  67. `script.timeout = ${/** @type {number} */ (loadTimeout) / 1000};`,
  68. `if (${RuntimeGlobals.scriptNonce}) {`,
  69. Template.indent(
  70. `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  71. ),
  72. "}",
  73. uniqueName
  74. ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);'
  75. : "",
  76. this._withFetchPriority
  77. ? Template.asString([
  78. "if(fetchPriority) {",
  79. Template.indent(
  80. 'script.setAttribute("fetchpriority", fetchPriority);'
  81. ),
  82. "}"
  83. ])
  84. : "",
  85. `script.src = ${
  86. this._withCreateScriptUrl
  87. ? `${RuntimeGlobals.createScriptUrl}(url)`
  88. : "url"
  89. };`,
  90. crossOriginLoading
  91. ? crossOriginLoading === "use-credentials"
  92. ? 'script.crossOrigin = "use-credentials";'
  93. : Template.asString([
  94. "if (script.src.indexOf(window.location.origin + '/') !== 0) {",
  95. Template.indent(
  96. `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
  97. ),
  98. "}"
  99. ])
  100. : ""
  101. ]);
  102. return Template.asString([
  103. "var inProgress = {};",
  104. uniqueName
  105. ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};`
  106. : "// data-webpack is not used as build has no uniqueName",
  107. "// loadScript function to load a script via script tag",
  108. `${fn} = ${runtimeTemplate.basicFunction(
  109. `url, done, key, chunkId${
  110. this._withFetchPriority ? ", fetchPriority" : ""
  111. }`,
  112. [
  113. "if(inProgress[url]) { inProgress[url].push(done); return; }",
  114. "var script, needAttach;",
  115. "if(key !== undefined) {",
  116. Template.indent([
  117. 'var scripts = document.getElementsByTagName("script");',
  118. "for(var i = 0; i < scripts.length; i++) {",
  119. Template.indent([
  120. "var s = scripts[i];",
  121. `if(s.getAttribute("src") == url${
  122. uniqueName
  123. ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key'
  124. : ""
  125. }) { script = s; break; }`
  126. ]),
  127. "}"
  128. ]),
  129. "}",
  130. "if(!script) {",
  131. Template.indent([
  132. "needAttach = true;",
  133. createScript.call(code, /** @type {Chunk} */ (this.chunk))
  134. ]),
  135. "}",
  136. "inProgress[url] = [done];",
  137. "var onScriptComplete = " +
  138. runtimeTemplate.basicFunction(
  139. "prev, event",
  140. Template.asString([
  141. "// avoid mem leaks in IE.",
  142. "script.onerror = script.onload = null;",
  143. "clearTimeout(timeout);",
  144. "var doneFns = inProgress[url];",
  145. "delete inProgress[url];",
  146. "script.parentNode && script.parentNode.removeChild(script);",
  147. `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction(
  148. "fn(event)",
  149. "fn"
  150. )});`,
  151. "if(prev) return prev(event);"
  152. ])
  153. ),
  154. `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`,
  155. "script.onerror = onScriptComplete.bind(null, script.onerror);",
  156. "script.onload = onScriptComplete.bind(null, script.onload);",
  157. "needAttach && document.head.appendChild(script);"
  158. ]
  159. )};`
  160. ]);
  161. }
  162. }
  163. module.exports = LoadScriptRuntimeModule;