html-minifier.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * The MIT License (MIT)
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. */
  25. // Derived from the work of Kirill Maltsev - https://github.com/posthtml/htmlnano
  26. /* global Node, NodeFilter */
  27. this.htmlMinifier = this.htmlMinifier || (() => {
  28. // Source: https://github.com/kangax/html-minifier/issues/63
  29. const booleanAttributes = [
  30. "allowfullscreen",
  31. "async",
  32. "autofocus",
  33. "autoplay",
  34. "checked",
  35. "compact",
  36. "controls",
  37. "declare",
  38. "default",
  39. "defaultchecked",
  40. "defaultmuted",
  41. "defaultselected",
  42. "defer",
  43. "disabled",
  44. "enabled",
  45. "formnovalidate",
  46. "hidden",
  47. "indeterminate",
  48. "inert",
  49. "ismap",
  50. "itemscope",
  51. "loop",
  52. "multiple",
  53. "muted",
  54. "nohref",
  55. "noresize",
  56. "noshade",
  57. "novalidate",
  58. "nowrap",
  59. "open",
  60. "pauseonexit",
  61. "readonly",
  62. "required",
  63. "reversed",
  64. "scoped",
  65. "seamless",
  66. "selected",
  67. "sortable",
  68. "truespeed",
  69. "typemustmatch",
  70. "visible"
  71. ];
  72. const noWhitespaceCollapseElements = ["script", "style", "pre", "textarea"];
  73. // Source: https://www.w3.org/TR/html4/sgml/dtd.html#events (Generic Attributes)
  74. const safeToRemoveAttrs = [
  75. "id",
  76. "class",
  77. "style",
  78. "lang",
  79. "dir",
  80. "onclick",
  81. "ondblclick",
  82. "onmousedown",
  83. "onmouseup",
  84. "onmouseover",
  85. "onmousemove",
  86. "onmouseout",
  87. "onkeypress",
  88. "onkeydown",
  89. "onkeyup"
  90. ];
  91. const redundantAttributes = {
  92. "form": {
  93. "method": "get"
  94. },
  95. "script": {
  96. "language": "javascript",
  97. "type": "text/javascript",
  98. // Remove attribute if the function returns false
  99. "charset": node => {
  100. // The charset attribute only really makes sense on “external” SCRIPT elements:
  101. // http://perfectionkills.com/optimizing-html/#8_script_charset
  102. return !node.getAttribute("src");
  103. }
  104. },
  105. "style": {
  106. "media": "all",
  107. "type": "text/css"
  108. },
  109. "link": {
  110. "media": "all"
  111. }
  112. };
  113. const REGEXP_WHITESPACE = /[ \t\f\r]+/g;
  114. const REGEXP_NEWLINE = /[\n]+/g;
  115. const REGEXP_ENDS_WHITESPACE = /^\s+$/;
  116. const modules = [
  117. collapseBooleanAttributes,
  118. mergeTextNodes,
  119. collapseWhitespace,
  120. removeComments,
  121. removeEmptyAttributes,
  122. removeRedundantAttributes,
  123. compressJSONLD,
  124. node => mergeElements(node, "style", (node, previousSibling) => node.parentElement && node.parentElement.tagName == "HEAD" && node.media == previousSibling.media && node.title == previousSibling.title)
  125. ];
  126. return {
  127. process: (doc, options) => {
  128. removeEmptyInlineElements(doc);
  129. const nodesWalker = doc.createTreeWalker(doc.documentElement, NodeFilter.SHOW_ALL, null, false);
  130. let node = nodesWalker.nextNode();
  131. while (node) {
  132. const deletedNode = modules.find(module => module(node, options));
  133. const previousNode = node;
  134. node = nodesWalker.nextNode();
  135. if (deletedNode) {
  136. previousNode.remove();
  137. }
  138. }
  139. }
  140. };
  141. function collapseBooleanAttributes(node) {
  142. if (node.nodeType == Node.ELEMENT_NODE) {
  143. Array.from(node.attributes).forEach(attribute => {
  144. if (booleanAttributes.includes(attribute.name)) {
  145. node.setAttribute(attribute.name, "");
  146. }
  147. });
  148. }
  149. }
  150. function mergeTextNodes(node) {
  151. if (node.nodeType == Node.TEXT_NODE) {
  152. if (node.previousSibling && node.previousSibling.nodeType == Node.TEXT_NODE) {
  153. node.textContent = node.previousSibling.textContent + node.textContent;
  154. node.previousSibling.remove();
  155. }
  156. }
  157. }
  158. function mergeElements(node, tagName, acceptMerge) {
  159. if (node.nodeType == Node.ELEMENT_NODE && node.tagName.toLowerCase() == tagName.toLowerCase()) {
  160. let previousSibling = node.previousSibling;
  161. const previousSiblings = [];
  162. while (previousSibling && previousSibling.nodeType == Node.TEXT_NODE && !previousSibling.textContent.trim()) {
  163. previousSiblings.push(previousSibling);
  164. previousSibling = previousSibling.previousSibling;
  165. }
  166. if (previousSibling && previousSibling.nodeType == Node.ELEMENT_NODE && previousSibling.tagName == node.tagName && acceptMerge(node, previousSibling)) {
  167. node.textContent = previousSibling.textContent + node.textContent;
  168. previousSiblings.forEach(node => node.remove());
  169. previousSibling.remove();
  170. }
  171. }
  172. }
  173. function collapseWhitespace(node, options) {
  174. if (node.nodeType == Node.TEXT_NODE) {
  175. let element = node.parentElement;
  176. const spacePreserved = element.getAttribute(options.preservedSpaceAttributeName) == "";
  177. const textContent = node.textContent;
  178. let noWhitespace = !spacePreserved && noWhitespaceCollapse(element);
  179. while (noWhitespace) {
  180. element = element.parentElement;
  181. noWhitespace = element && noWhitespaceCollapse(element);
  182. }
  183. if ((!element || noWhitespace) && textContent.length > 1) {
  184. node.textContent = textContent.replace(REGEXP_WHITESPACE, getWhiteSpace(node)).replace(REGEXP_NEWLINE, "\n");
  185. }
  186. }
  187. }
  188. function getWhiteSpace(node) {
  189. return node.parentElement && node.parentElement.tagName == "HEAD" ? "\n" : " ";
  190. }
  191. function noWhitespaceCollapse(element) {
  192. return element && !noWhitespaceCollapseElements.includes(element.tagName.toLowerCase());
  193. }
  194. function removeComments(node) {
  195. if (node.nodeType == Node.COMMENT_NODE) {
  196. return !node.textContent.toLowerCase().trim().startsWith("[if");
  197. }
  198. }
  199. function removeEmptyAttributes(node) {
  200. if (node.nodeType == Node.ELEMENT_NODE) {
  201. Array.from(node.attributes).forEach(attribute => {
  202. if (safeToRemoveAttrs.includes(attribute.name.toLowerCase())) {
  203. const attributeValue = node.getAttribute(attribute.name);
  204. if (attributeValue == "" || (attributeValue || "").match(REGEXP_ENDS_WHITESPACE)) {
  205. node.removeAttribute(attribute.name);
  206. }
  207. }
  208. });
  209. }
  210. }
  211. function removeRedundantAttributes(node) {
  212. if (node.nodeType == Node.ELEMENT_NODE) {
  213. const tagRedundantAttributes = redundantAttributes[node.tagName.toLowerCase()];
  214. if (tagRedundantAttributes) {
  215. Object.keys(tagRedundantAttributes).forEach(redundantAttributeName => {
  216. const tagRedundantAttributeValue = tagRedundantAttributes[redundantAttributeName];
  217. if (typeof tagRedundantAttributeValue == "function" ? tagRedundantAttributeValue(node) : node.getAttribute(redundantAttributeName) == tagRedundantAttributeValue) {
  218. node.removeAttribute(redundantAttributeName);
  219. }
  220. });
  221. }
  222. }
  223. }
  224. function compressJSONLD(node) {
  225. if (node.nodeType == Node.ELEMENT_NODE && node.tagName == "SCRIPT" && node.type == "application/ld+json" && node.textContent.trim()) {
  226. try {
  227. node.textContent = JSON.stringify(JSON.parse(node.textContent));
  228. } catch (error) {
  229. /* ignored */
  230. }
  231. }
  232. }
  233. function removeEmptyInlineElements(doc) {
  234. doc.querySelectorAll("style, script:not([src]), noscript").forEach(element => {
  235. if (!element.textContent.trim()) {
  236. element.remove();
  237. }
  238. });
  239. }
  240. })();