critters.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  2. var path = _interopDefault(require('path'));
  3. var fs = require('fs');
  4. var prettyBytes = _interopDefault(require('pretty-bytes'));
  5. var parse5 = _interopDefault(require('parse5'));
  6. var cssSelect = require('css-select');
  7. var treeAdapter = _interopDefault(require('parse5-htmlparser2-tree-adapter'));
  8. var postcss = require('postcss');
  9. var chalk = _interopDefault(require('chalk'));
  10. /**
  11. * Copyright 2018 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy of
  15. * the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. const PARSE5_OPTS = {
  26. treeAdapter
  27. };
  28. /**
  29. * Parse HTML into a mutable, serializable DOM Document.
  30. * The DOM implementation is an htmlparser2 DOM enhanced with basic DOM mutation methods.
  31. * @param {String} html HTML to parse into a Document instance
  32. */
  33. function createDocument(html) {
  34. const document =
  35. /** @type {HTMLDocument} */
  36. parse5.parse(html, PARSE5_OPTS);
  37. defineProperties(document, DocumentExtensions); // Extend Element.prototype with DOM manipulation methods.
  38. const scratch = document.createElement('div'); // Get a reference to the base Node class - used by createTextNode()
  39. document.$$Node = scratch.constructor;
  40. const elementProto = Object.getPrototypeOf(scratch);
  41. defineProperties(elementProto, ElementExtensions);
  42. elementProto.ownerDocument = document;
  43. return document;
  44. }
  45. /**
  46. * Serialize a Document to an HTML String
  47. * @param {HTMLDocument} document A Document, such as one created via `createDocument()`
  48. */
  49. function serializeDocument(document) {
  50. return parse5.serialize(document, PARSE5_OPTS);
  51. }
  52. /** @typedef {treeAdapter.Document & typeof ElementExtensions} HTMLDocument */
  53. /**
  54. * Methods and descriptors to mix into Element.prototype
  55. * @private
  56. */
  57. const ElementExtensions = {
  58. /** @extends treeAdapter.Element.prototype */
  59. nodeName: {
  60. get() {
  61. return this.tagName.toUpperCase();
  62. }
  63. },
  64. id: reflectedProperty('id'),
  65. className: reflectedProperty('class'),
  66. insertBefore(child, referenceNode) {
  67. if (!referenceNode) return this.appendChild(child);
  68. treeAdapter.insertBefore(this, child, referenceNode);
  69. return child;
  70. },
  71. appendChild(child) {
  72. treeAdapter.appendChild(this, child);
  73. return child;
  74. },
  75. removeChild(child) {
  76. treeAdapter.detachNode(child);
  77. },
  78. remove() {
  79. treeAdapter.detachNode(this);
  80. },
  81. textContent: {
  82. get() {
  83. return getText(this);
  84. },
  85. set(text) {
  86. this.children = [];
  87. treeAdapter.insertText(this, text);
  88. }
  89. },
  90. setAttribute(name, value) {
  91. if (this.attribs == null) this.attribs = {};
  92. if (value == null) value = '';
  93. this.attribs[name] = value;
  94. },
  95. removeAttribute(name) {
  96. if (this.attribs != null) {
  97. delete this.attribs[name];
  98. }
  99. },
  100. getAttribute(name) {
  101. return this.attribs != null && this.attribs[name];
  102. },
  103. hasAttribute(name) {
  104. return this.attribs != null && this.attribs[name] != null;
  105. },
  106. getAttributeNode(name) {
  107. const value = this.getAttribute(name);
  108. if (value != null) return {
  109. specified: true,
  110. value
  111. };
  112. }
  113. };
  114. /**
  115. * Methods and descriptors to mix into the global document instance
  116. * @private
  117. */
  118. const DocumentExtensions = {
  119. /** @extends treeAdapter.Document.prototype */
  120. // document is just an Element in htmlparser2, giving it a nodeType of ELEMENT_NODE.
  121. // TODO: verify if these are needed for css-select
  122. nodeType: {
  123. get() {
  124. return 9;
  125. }
  126. },
  127. contentType: {
  128. get() {
  129. return 'text/html';
  130. }
  131. },
  132. nodeName: {
  133. get() {
  134. return '#document';
  135. }
  136. },
  137. documentElement: {
  138. get() {
  139. // Find the first <html> element within the document
  140. return this.childNodes.filter(child => String(child.tagName).toLowerCase() === 'html');
  141. }
  142. },
  143. compatMode: {
  144. get() {
  145. const compatMode = {
  146. 'no-quirks': 'CSS1Compat',
  147. quirks: 'BackCompat',
  148. 'limited-quirks': 'CSS1Compat'
  149. };
  150. return compatMode[treeAdapter.getDocumentMode(this)];
  151. }
  152. },
  153. head: {
  154. get() {
  155. return this.querySelector('head');
  156. }
  157. },
  158. body: {
  159. get() {
  160. return this.querySelector('body');
  161. }
  162. },
  163. createElement(name) {
  164. return treeAdapter.createElement(name, null, []);
  165. },
  166. createTextNode(text) {
  167. // there is no dedicated createTextNode equivalent exposed in htmlparser2's DOM
  168. const Node = this.$$Node;
  169. return new Node({
  170. type: 'text',
  171. data: text,
  172. parent: null,
  173. prev: null,
  174. next: null
  175. });
  176. },
  177. querySelector(sel) {
  178. return cssSelect.selectOne(sel, this.documentElement);
  179. },
  180. querySelectorAll(sel) {
  181. if (sel === ':root') {
  182. return this;
  183. }
  184. return cssSelect.selectAll(sel, this.documentElement);
  185. }
  186. };
  187. /**
  188. * Essentially `Object.defineProperties()`, except function values are assigned as value descriptors for convenience.
  189. * @private
  190. */
  191. function defineProperties(obj, properties) {
  192. for (const i in properties) {
  193. const value = properties[i];
  194. Object.defineProperty(obj, i, typeof value === 'function' ? {
  195. value
  196. } : value);
  197. }
  198. }
  199. /**
  200. * Create a property descriptor defining a getter/setter pair alias for a named attribute.
  201. * @private
  202. */
  203. function reflectedProperty(attributeName) {
  204. return {
  205. get() {
  206. return this.getAttribute(attributeName);
  207. },
  208. set(value) {
  209. this.setAttribute(attributeName, value);
  210. }
  211. };
  212. }
  213. /**
  214. * Helper to get the text content of a node
  215. * https://github.com/fb55/domutils/blob/master/src/stringify.ts#L21
  216. * @private
  217. */
  218. function getText(node) {
  219. if (Array.isArray(node)) return node.map(getText).join('');
  220. if (treeAdapter.isElementNode(node)) return node.name === 'br' ? '\n' : getText(node.children);
  221. if (treeAdapter.isTextNode(node)) return node.data;
  222. return '';
  223. }
  224. /**
  225. * Copyright 2018 Google LLC
  226. *
  227. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  228. * use this file except in compliance with the License. You may obtain a copy of
  229. * the License at
  230. *
  231. * http://www.apache.org/licenses/LICENSE-2.0
  232. *
  233. * Unless required by applicable law or agreed to in writing, software
  234. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  235. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  236. * License for the specific language governing permissions and limitations under
  237. * the License.
  238. */
  239. /**
  240. * Parse a textual CSS Stylesheet into a Stylesheet instance.
  241. * Stylesheet is a mutable postcss AST with format similar to CSSOM.
  242. * @see https://github.com/postcss/postcss/
  243. * @private
  244. * @param {String} stylesheet
  245. * @returns {css.Stylesheet} ast
  246. */
  247. function parseStylesheet(stylesheet) {
  248. return postcss.parse(stylesheet);
  249. }
  250. /**
  251. * Serialize a postcss Stylesheet to a String of CSS.
  252. * @private
  253. * @param {css.Stylesheet} ast A Stylesheet to serialize, such as one returned from `parseStylesheet()`
  254. * @param {Object} options Options used by the stringify logic
  255. * @param {Boolean} [options.compress] Compress CSS output (removes comments, whitespace, etc)
  256. */
  257. function serializeStylesheet(ast, options) {
  258. let cssStr = '';
  259. postcss.stringify(ast, (result, node, type) => {
  260. var _node$raws;
  261. if (!options.compress) {
  262. cssStr += result;
  263. return;
  264. } // Simple minification logic
  265. if ((node == null ? void 0 : node.type) === 'comment') return;
  266. if ((node == null ? void 0 : node.type) === 'decl') {
  267. const prefix = node.prop + node.raws.between;
  268. cssStr += result.replace(prefix, prefix.trim());
  269. return;
  270. }
  271. if (type === 'start') {
  272. if (node.type === 'rule' && node.selectors) {
  273. cssStr += node.selectors.join(',') + '{';
  274. } else {
  275. cssStr += result.replace(/\s\{$/, '{');
  276. }
  277. return;
  278. }
  279. if (type === 'end' && result === '}' && node != null && (_node$raws = node.raws) != null && _node$raws.semicolon) {
  280. cssStr = cssStr.slice(0, -1);
  281. }
  282. cssStr += result.trim();
  283. });
  284. return cssStr;
  285. }
  286. /**
  287. * Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them.
  288. * This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets).
  289. * @private
  290. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  291. * @returns {(rule) => void} nonDestructiveIterator
  292. */
  293. function markOnly(predicate) {
  294. return rule => {
  295. const sel = rule.selectors;
  296. if (predicate(rule) === false) {
  297. rule.$$remove = true;
  298. }
  299. rule.$$markedSelectors = rule.selectors;
  300. if (rule._other) {
  301. rule._other.$$markedSelectors = rule._other.selectors;
  302. }
  303. rule.selectors = sel;
  304. };
  305. }
  306. /**
  307. * Apply filtered selectors to a rule from a previous markOnly run.
  308. * @private
  309. * @param {css.Rule} rule The Rule to apply marked selectors to (if they exist).
  310. */
  311. function applyMarkedSelectors(rule) {
  312. if (rule.$$markedSelectors) {
  313. rule.selectors = rule.$$markedSelectors;
  314. }
  315. if (rule._other) {
  316. applyMarkedSelectors(rule._other);
  317. }
  318. }
  319. /**
  320. * Recursively walk all rules in a stylesheet.
  321. * @private
  322. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  323. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  324. */
  325. function walkStyleRules(node, iterator) {
  326. node.nodes = node.nodes.filter(rule => {
  327. if (hasNestedRules(rule)) {
  328. walkStyleRules(rule, iterator);
  329. }
  330. rule._other = undefined;
  331. rule.filterSelectors = filterSelectors;
  332. return iterator(rule) !== false;
  333. });
  334. }
  335. /**
  336. * Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate.
  337. * @private
  338. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  339. * @param {css.Rule} node2 A second tree identical to `node`
  340. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second.
  341. */
  342. function walkStyleRulesWithReverseMirror(node, node2, iterator) {
  343. if (node2 === null) return walkStyleRules(node, iterator);
  344. [node.nodes, node2.nodes] = splitFilter(node.nodes, node2.nodes, (rule, index, rules, rules2) => {
  345. const rule2 = rules2[index];
  346. if (hasNestedRules(rule)) {
  347. walkStyleRulesWithReverseMirror(rule, rule2, iterator);
  348. }
  349. rule._other = rule2;
  350. rule.filterSelectors = filterSelectors;
  351. return iterator(rule) !== false;
  352. });
  353. } // Checks if a node has nested rules, like @media
  354. // @keyframes are an exception since they are evaluated as a whole
  355. function hasNestedRules(rule) {
  356. return rule.nodes && rule.nodes.length && rule.nodes.some(n => n.type === 'rule' || n.type === 'atrule') && rule.name !== 'keyframes' && rule.name !== '-webkit-keyframes';
  357. } // Like [].filter(), but applies the opposite filtering result to a second copy of the Array without a second pass.
  358. // This is just a quicker version of generating the compliment of the set returned from a filter operation.
  359. function splitFilter(a, b, predicate) {
  360. const aOut = [];
  361. const bOut = [];
  362. for (let index = 0; index < a.length; index++) {
  363. if (predicate(a[index], index, a, b)) {
  364. aOut.push(a[index]);
  365. } else {
  366. bOut.push(a[index]);
  367. }
  368. }
  369. return [aOut, bOut];
  370. } // can be invoked on a style rule to subset its selectors (with reverse mirroring)
  371. function filterSelectors(predicate) {
  372. if (this._other) {
  373. const [a, b] = splitFilter(this.selectors, this._other.selectors, predicate);
  374. this.selectors = a;
  375. this._other.selectors = b;
  376. } else {
  377. this.selectors = this.selectors.filter(predicate);
  378. }
  379. }
  380. const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'silent'];
  381. const defaultLogger = {
  382. trace(msg) {
  383. console.trace(msg);
  384. },
  385. debug(msg) {
  386. console.debug(msg);
  387. },
  388. warn(msg) {
  389. console.warn(chalk.yellow(msg));
  390. },
  391. error(msg) {
  392. console.error(chalk.bold.red(msg));
  393. },
  394. info(msg) {
  395. console.info(chalk.bold.blue(msg));
  396. },
  397. silent() {}
  398. };
  399. function createLogger(logLevel) {
  400. const logLevelIdx = LOG_LEVELS.indexOf(logLevel);
  401. return LOG_LEVELS.reduce((logger, type, index) => {
  402. if (index >= logLevelIdx) {
  403. logger[type] = defaultLogger[type];
  404. } else {
  405. logger[type] = defaultLogger.silent;
  406. }
  407. return logger;
  408. }, {});
  409. }
  410. /**
  411. * Copyright 2018 Google LLC
  412. *
  413. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  414. * use this file except in compliance with the License. You may obtain a copy of
  415. * the License at
  416. *
  417. * http://www.apache.org/licenses/LICENSE-2.0
  418. *
  419. * Unless required by applicable law or agreed to in writing, software
  420. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  421. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  422. * License for the specific language governing permissions and limitations under
  423. * the License.
  424. */
  425. /**
  426. * The mechanism to use for lazy-loading stylesheets.
  427. *
  428. * Note: <kbd>JS</kbd> indicates a strategy requiring JavaScript (falls back to `<noscript>` unless disabled).
  429. *
  430. * - **default:** Move stylesheet links to the end of the document and insert preload meta tags in their place.
  431. * - **"body":** Move all external stylesheet links to the end of the document.
  432. * - **"media":** Load stylesheets asynchronously by adding `media="not x"` and removing once loaded. <kbd>JS</kbd>
  433. * - **"swap":** Convert stylesheet links to preloads that swap to `rel="stylesheet"` once loaded ([details](https://www.filamentgroup.com/lab/load-css-simpler/#the-code)). <kbd>JS</kbd>
  434. * - **"swap-high":** Use `<link rel="alternate stylesheet preload">` and swap to `rel="stylesheet"` once loaded ([details](http://filamentgroup.github.io/loadCSS/test/new-high.html)). <kbd>JS</kbd>
  435. * - **"js":** Inject an asynchronous CSS loader similar to [LoadCSS](https://github.com/filamentgroup/loadCSS) and use it to load stylesheets. <kbd>JS</kbd>
  436. * - **"js-lazy":** Like `"js"`, but the stylesheet is disabled until fully loaded.
  437. * - **false:** Disables adding preload tags.
  438. * @typedef {(default|'body'|'media'|'swap'|'swap-high'|'js'|'js-lazy')} PreloadStrategy
  439. * @public
  440. */
  441. /**
  442. * Controls which keyframes rules are inlined.
  443. *
  444. * - **"critical":** _(default)_ inline keyframes rules that are used by the critical CSS.
  445. * - **"all":** Inline all keyframes rules.
  446. * - **"none":** Remove all keyframes rules.
  447. * @typedef {('critical'|'all'|'none')} KeyframeStrategy
  448. * @private
  449. * @property {String} keyframes Which {@link KeyframeStrategy keyframe strategy} to use (default: `critical`)_
  450. */
  451. /**
  452. * Controls log level of the plugin. Specifies the level the logger should use. A logger will
  453. * not produce output for any log level beneath the specified level. Available levels and order
  454. * are:
  455. *
  456. * - **"info"** _(default)_
  457. * - **"warn"**
  458. * - **"error"**
  459. * - **"trace"**
  460. * - **"debug"**
  461. * - **"silent"**
  462. * @typedef {('info'|'warn'|'error'|'trace'|'debug'|'silent')} LogLevel
  463. * @public
  464. */
  465. /**
  466. * Custom logger interface:
  467. * @typedef {object} Logger
  468. * @public
  469. * @property {function(String)} trace - Prints a trace message
  470. * @property {function(String)} debug - Prints a debug message
  471. * @property {function(String)} info - Prints an information message
  472. * @property {function(String)} warn - Prints a warning message
  473. * @property {function(String)} error - Prints an error message
  474. */
  475. /**
  476. * All optional. Pass them to `new Critters({ ... })`.
  477. * @public
  478. * @typedef Options
  479. * @property {String} path Base path location of the CSS files _(default: `''`)_
  480. * @property {String} publicPath Public path of the CSS resources. This prefix is removed from the href _(default: `''`)_
  481. * @property {Boolean} external Inline styles from external stylesheets _(default: `true`)_
  482. * @property {Number} inlineThreshold Inline external stylesheets smaller than a given size _(default: `0`)_
  483. * @property {Number} minimumExternalSize If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_
  484. * @property {Boolean} pruneSource Remove inlined rules from the external stylesheet _(default: `false`)_
  485. * @property {Boolean} mergeStylesheets Merged inlined stylesheets into a single `<style>` tag _(default: `true`)_
  486. * @property {String[]} additionalStylesheets Glob for matching other stylesheets to be used while looking for critical CSS.
  487. * @property {String} preload Which {@link PreloadStrategy preload strategy} to use
  488. * @property {Boolean} noscriptFallback Add `<noscript>` fallback to JS-based strategies
  489. * @property {Boolean} inlineFonts Inline critical font-face rules _(default: `false`)_
  490. * @property {Boolean} preloadFonts Preloads critical fonts _(default: `true`)_
  491. * @property {Boolean} fonts Shorthand for setting `inlineFonts` + `preloadFonts`
  492. * - Values:
  493. * - `true` to inline critical font-face rules and preload the fonts
  494. * - `false` to don't inline any font-face rules and don't preload fonts
  495. * @property {String} keyframes Controls which keyframes rules are inlined.
  496. * - Values:
  497. * - `"critical"`: _(default)_ inline keyframes rules used by the critical CSS
  498. * - `"all"` inline all keyframes rules
  499. * - `"none"` remove all keyframes rules
  500. * @property {Boolean} compress Compress resulting critical CSS _(default: `true`)_
  501. * @property {String} logLevel Controls {@link LogLevel log level} of the plugin _(default: `"info"`)_
  502. * @property {object} logger Provide a custom logger interface {@link Logger logger}
  503. */
  504. class Critters {
  505. /** @private */
  506. constructor(options) {
  507. this.options = Object.assign({
  508. logLevel: 'info',
  509. path: '',
  510. publicPath: '',
  511. reduceInlineStyles: true,
  512. pruneSource: false,
  513. additionalStylesheets: []
  514. }, options || {});
  515. this.urlFilter = this.options.filter;
  516. if (this.urlFilter instanceof RegExp) {
  517. this.urlFilter = this.urlFilter.test.bind(this.urlFilter);
  518. }
  519. this.logger = this.options.logger || createLogger(this.options.logLevel);
  520. }
  521. /**
  522. * Read the contents of a file from the specified filesystem or disk
  523. */
  524. readFile(filename) {
  525. const fs$1 = this.fs;
  526. return new Promise((resolve, reject) => {
  527. const callback = (err, data) => {
  528. if (err) reject(err);else resolve(data);
  529. };
  530. if (fs$1 && fs$1.readFile) {
  531. fs$1.readFile(filename, callback);
  532. } else {
  533. fs.readFile(filename, 'utf8', callback);
  534. }
  535. });
  536. }
  537. /**
  538. * Apply critical CSS processing to the html
  539. */
  540. async process(html) {
  541. const start = process.hrtime.bigint(); // Parse the generated HTML in a DOM we can mutate
  542. const document = createDocument(html);
  543. if (this.options.additionalStylesheets.length > 0) {
  544. this.embedAdditionalStylesheet(document);
  545. } // `external:false` skips processing of external sheets
  546. if (this.options.external !== false) {
  547. const externalSheets = [].slice.call(document.querySelectorAll('link[rel="stylesheet"]'));
  548. await Promise.all(externalSheets.map(link => this.embedLinkedStylesheet(link, document)));
  549. } // go through all the style tags in the document and reduce them to only critical CSS
  550. const styles = this.getAffectedStyleTags(document);
  551. await Promise.all(styles.map(style => this.processStyle(style, document)));
  552. if (this.options.mergeStylesheets !== false && styles.length !== 0) {
  553. await this.mergeStylesheets(document);
  554. } // serialize the document back to HTML and we're done
  555. const output = serializeDocument(document);
  556. const end = process.hrtime.bigint();
  557. this.logger.info('Time ' + parseFloat(end - start) / 1000000.0);
  558. return output;
  559. }
  560. /**
  561. * Get the style tags that need processing
  562. */
  563. getAffectedStyleTags(document) {
  564. const styles = [].slice.call(document.querySelectorAll('style')); // `inline:false` skips processing of inline stylesheets
  565. if (this.options.reduceInlineStyles === false) {
  566. return styles.filter(style => style.$$external);
  567. }
  568. return styles;
  569. }
  570. async mergeStylesheets(document) {
  571. const styles = this.getAffectedStyleTags(document);
  572. if (styles.length === 0) {
  573. this.logger.warn('Merging inline stylesheets into a single <style> tag skipped, no inline stylesheets to merge');
  574. return;
  575. }
  576. const first = styles[0];
  577. let sheet = first.textContent;
  578. for (let i = 1; i < styles.length; i++) {
  579. const node = styles[i];
  580. sheet += node.textContent;
  581. node.remove();
  582. }
  583. first.textContent = sheet;
  584. }
  585. /**
  586. * Given href, find the corresponding CSS asset
  587. */
  588. async getCssAsset(href) {
  589. const outputPath = this.options.path;
  590. const publicPath = this.options.publicPath; // CHECK - the output path
  591. // path on disk (with output.publicPath removed)
  592. let normalizedPath = href.replace(/^\//, '');
  593. const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/';
  594. if (normalizedPath.indexOf(pathPrefix) === 0) {
  595. normalizedPath = normalizedPath.substring(pathPrefix.length).replace(/^\//, '');
  596. } // Ignore remote stylesheets
  597. if (/^https?:\/\//.test(normalizedPath) || href.startsWith('//')) {
  598. return undefined;
  599. }
  600. const filename = path.resolve(outputPath, normalizedPath);
  601. let sheet;
  602. try {
  603. sheet = await this.readFile(filename);
  604. } catch (e) {
  605. this.logger.warn(`Unable to locate stylesheet: ${filename}`);
  606. }
  607. return sheet;
  608. }
  609. checkInlineThreshold(link, style, sheet) {
  610. if (this.options.inlineThreshold && sheet.length < this.options.inlineThreshold) {
  611. const href = style.$$name;
  612. style.$$reduce = false;
  613. this.logger.info(`\u001b[32mInlined all of ${href} (${sheet.length} was below the threshold of ${this.options.inlineThreshold})\u001b[39m`);
  614. link.remove();
  615. return true;
  616. }
  617. return false;
  618. }
  619. /**
  620. * Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`)
  621. */
  622. async embedAdditionalStylesheet(document) {
  623. const styleSheetsIncluded = [];
  624. const sources = await Promise.all(this.options.additionalStylesheets.map(cssFile => {
  625. if (styleSheetsIncluded.includes(cssFile)) {
  626. return;
  627. }
  628. styleSheetsIncluded.push(cssFile);
  629. const style = document.createElement('style');
  630. style.$$external = true;
  631. return this.getCssAsset(cssFile, style).then(sheet => [sheet, style]);
  632. }));
  633. sources.forEach(([sheet, style]) => {
  634. if (!sheet) return;
  635. style.textContent = sheet;
  636. document.head.appendChild(style);
  637. });
  638. }
  639. /**
  640. * Inline the target stylesheet referred to by a <link rel="stylesheet"> (assuming it passes `options.filter`)
  641. */
  642. async embedLinkedStylesheet(link, document) {
  643. const href = link.getAttribute('href');
  644. const media = link.getAttribute('media');
  645. const preloadMode = this.options.preload; // skip filtered resources, or network resources if no filter is provided
  646. if (this.urlFilter ? this.urlFilter(href) : !(href || '').match(/\.css$/)) {
  647. return Promise.resolve();
  648. } // the reduced critical CSS gets injected into a new <style> tag
  649. const style = document.createElement('style');
  650. style.$$external = true;
  651. const sheet = await this.getCssAsset(href, style);
  652. if (!sheet) {
  653. return;
  654. }
  655. style.textContent = sheet;
  656. style.$$name = href;
  657. style.$$links = [link];
  658. link.parentNode.insertBefore(style, link);
  659. if (this.checkInlineThreshold(link, style, sheet)) {
  660. return;
  661. } // CSS loader is only injected for the first sheet, then this becomes an empty string
  662. let cssLoaderPreamble = "function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}";
  663. const lazy = preloadMode === 'js-lazy';
  664. if (lazy) {
  665. cssLoaderPreamble = cssLoaderPreamble.replace('l.href', "l.media='print';l.onload=function(){l.media=m};l.href");
  666. } // Allow disabling any mutation of the stylesheet link:
  667. if (preloadMode === false) return;
  668. let noscriptFallback = false;
  669. if (preloadMode === 'body') {
  670. document.body.appendChild(link);
  671. } else {
  672. link.setAttribute('rel', 'preload');
  673. link.setAttribute('as', 'style');
  674. if (preloadMode === 'js' || preloadMode === 'js-lazy') {
  675. const script = document.createElement('script');
  676. const js = `${cssLoaderPreamble}$loadcss(${JSON.stringify(href)}${lazy ? ',' + JSON.stringify(media || 'all') : ''})`; // script.appendChild(document.createTextNode(js));
  677. script.textContent = js;
  678. link.parentNode.insertBefore(script, link.nextSibling);
  679. style.$$links.push(script);
  680. cssLoaderPreamble = '';
  681. noscriptFallback = true;
  682. } else if (preloadMode === 'media') {
  683. // @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26
  684. link.setAttribute('rel', 'stylesheet');
  685. link.removeAttribute('as');
  686. link.setAttribute('media', 'print');
  687. link.setAttribute('onload', `this.media='${media || 'all'}'`);
  688. noscriptFallback = true;
  689. } else if (preloadMode === 'swap-high') {
  690. // @see http://filamentgroup.github.io/loadCSS/test/new-high.html
  691. link.setAttribute('rel', 'alternate stylesheet preload');
  692. link.setAttribute('title', 'styles');
  693. link.setAttribute('onload', `this.title='';this.rel='stylesheet'`);
  694. noscriptFallback = true;
  695. } else if (preloadMode === 'swap') {
  696. link.setAttribute('onload', "this.rel='stylesheet'");
  697. noscriptFallback = true;
  698. } else {
  699. const bodyLink = document.createElement('link');
  700. bodyLink.setAttribute('rel', 'stylesheet');
  701. if (media) bodyLink.setAttribute('media', media);
  702. bodyLink.setAttribute('href', href);
  703. document.body.appendChild(bodyLink);
  704. style.$$links.push(bodyLink);
  705. }
  706. }
  707. if (this.options.noscriptFallback !== false && noscriptFallback) {
  708. const noscript = document.createElement('noscript');
  709. const noscriptLink = document.createElement('link');
  710. noscriptLink.setAttribute('rel', 'stylesheet');
  711. noscriptLink.setAttribute('href', href);
  712. if (media) noscriptLink.setAttribute('media', media);
  713. noscript.appendChild(noscriptLink);
  714. link.parentNode.insertBefore(noscript, link.nextSibling);
  715. style.$$links.push(noscript);
  716. }
  717. }
  718. /**
  719. * Prune the source CSS files
  720. */
  721. pruneSource(style, before, sheetInverse) {
  722. // if external stylesheet would be below minimum size, just inline everything
  723. const minSize = this.options.minimumExternalSize;
  724. const name = style.$$name;
  725. if (minSize && sheetInverse.length < minSize) {
  726. this.logger.info(`\u001b[32mInlined all of ${name} (non-critical external stylesheet would have been ${sheetInverse.length}b, which was below the threshold of ${minSize})\u001b[39m`);
  727. style.textContent = before; // remove any associated external resources/loaders:
  728. if (style.$$links) {
  729. for (const link of style.$$links) {
  730. const parent = link.parentNode;
  731. if (parent) parent.removeChild(link);
  732. }
  733. }
  734. return true;
  735. }
  736. return false;
  737. }
  738. /**
  739. * Parse the stylesheet within a <style> element, then reduce it to contain only rules used by the document.
  740. */
  741. async processStyle(style, document) {
  742. if (style.$$reduce === false) return;
  743. const name = style.$$name ? style.$$name.replace(/^\//, '') : 'inline CSS';
  744. const options = this.options; // const document = style.ownerDocument;
  745. let keyframesMode = options.keyframes || 'critical'; // we also accept a boolean value for options.keyframes
  746. if (keyframesMode === true) keyframesMode = 'all';
  747. if (keyframesMode === false) keyframesMode = 'none';
  748. let sheet = style.textContent; // store a reference to the previous serialized stylesheet for reporting stats
  749. const before = sheet; // Skip empty stylesheets
  750. if (!sheet) return;
  751. const ast = parseStylesheet(sheet);
  752. const astInverse = options.pruneSource ? parseStylesheet(sheet) : null; // a string to search for font names (very loose)
  753. let criticalFonts = '';
  754. const failedSelectors = [];
  755. const criticalKeyframeNames = []; // Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
  756. // This first pass is also used to collect font and keyframe usage used in the second pass.
  757. walkStyleRules(ast, markOnly(rule => {
  758. if (rule.type === 'rule') {
  759. // Filter the selector list down to only those match
  760. rule.filterSelectors(sel => {
  761. // Strip pseudo-elements and pseudo-classes, since we only care that their associated elements exist.
  762. // This means any selector for a pseudo-element or having a pseudo-class will be inlined if the rest of the selector matches.
  763. if (sel === ':root' || sel.match(/^::?(before|after)$/)) {
  764. return true;
  765. }
  766. sel = sel.replace(/(?<!\\)::?[a-z-]+(?![a-z-(])/gi, '').replace(/::?not\(\s*\)/g, '').trim();
  767. if (!sel) return false;
  768. try {
  769. return document.querySelector(sel) != null;
  770. } catch (e) {
  771. failedSelectors.push(sel + ' -> ' + e.message);
  772. return false;
  773. }
  774. }); // If there are no matched selectors, remove the rule:
  775. if (!rule.selector) {
  776. return false;
  777. }
  778. if (rule.nodes) {
  779. for (let i = 0; i < rule.nodes.length; i++) {
  780. const decl = rule.nodes[i]; // detect used fonts
  781. if (decl.prop && decl.prop.match(/\bfont(-family)?\b/i)) {
  782. criticalFonts += ' ' + decl.value;
  783. } // detect used keyframes
  784. if (decl.prop === 'animation' || decl.prop === 'animation-name') {
  785. // @todo: parse animation declarations and extract only the name. for now we'll do a lazy match.
  786. const names = decl.value.split(/\s+/);
  787. for (let j = 0; j < names.length; j++) {
  788. const name = names[j].trim();
  789. if (name) criticalKeyframeNames.push(name);
  790. }
  791. }
  792. }
  793. }
  794. } // keep font rules, they're handled in the second pass:
  795. if (rule.type === 'atrule' && rule.name === 'font-face') return; // If there are no remaining rules, remove the whole rule:
  796. const rules = rule.nodes && rule.nodes.filter(rule => !rule.$$remove);
  797. return !rules || rules.length !== 0;
  798. }));
  799. if (failedSelectors.length !== 0) {
  800. this.logger.warn(`${failedSelectors.length} rules skipped due to selector errors:\n ${failedSelectors.join('\n ')}`);
  801. }
  802. const shouldPreloadFonts = options.fonts === true || options.preloadFonts === true;
  803. const shouldInlineFonts = options.fonts !== false && options.inlineFonts === true;
  804. const preloadedFonts = []; // Second pass, using data picked up from the first
  805. walkStyleRulesWithReverseMirror(ast, astInverse, rule => {
  806. // remove any rules marked in the first pass
  807. if (rule.$$remove === true) return false;
  808. applyMarkedSelectors(rule); // prune @keyframes rules
  809. if (rule.type === 'atrule' && rule.name === 'keyframes') {
  810. if (keyframesMode === 'none') return false;
  811. if (keyframesMode === 'all') return true;
  812. return criticalKeyframeNames.indexOf(rule.params) !== -1;
  813. } // prune @font-face rules
  814. if (rule.type === 'atrule' && rule.name === 'font-face') {
  815. let family, src;
  816. for (let i = 0; i < rule.nodes.length; i++) {
  817. const decl = rule.nodes[i];
  818. if (decl.prop === 'src') {
  819. // @todo parse this properly and generate multiple preloads with type="font/woff2" etc
  820. src = (decl.value.match(/url\s*\(\s*(['"]?)(.+?)\1\s*\)/) || [])[2];
  821. } else if (decl.prop === 'font-family') {
  822. family = decl.value;
  823. }
  824. }
  825. if (src && shouldPreloadFonts && preloadedFonts.indexOf(src) === -1) {
  826. preloadedFonts.push(src);
  827. const preload = document.createElement('link');
  828. preload.setAttribute('rel', 'preload');
  829. preload.setAttribute('as', 'font');
  830. preload.setAttribute('crossorigin', 'anonymous');
  831. preload.setAttribute('href', src.trim());
  832. document.head.appendChild(preload);
  833. } // if we're missing info, if the font is unused, or if critical font inlining is disabled, remove the rule:
  834. if (!family || !src || criticalFonts.indexOf(family) === -1 || !shouldInlineFonts) {
  835. return false;
  836. }
  837. }
  838. });
  839. sheet = serializeStylesheet(ast, {
  840. compress: this.options.compress !== false
  841. }); // If all rules were removed, get rid of the style element entirely
  842. if (sheet.trim().length === 0) {
  843. if (style.parentNode) {
  844. style.remove();
  845. }
  846. return;
  847. }
  848. let afterText = '';
  849. let styleInlinedCompletely = false;
  850. if (options.pruneSource) {
  851. const sheetInverse = serializeStylesheet(astInverse, {
  852. compress: this.options.compress !== false
  853. });
  854. styleInlinedCompletely = this.pruneSource(style, before, sheetInverse);
  855. if (styleInlinedCompletely) {
  856. const percent = sheetInverse.length / before.length * 100;
  857. afterText = `, reducing non-inlined size ${percent | 0}% to ${prettyBytes(sheetInverse.length)}`;
  858. }
  859. } // replace the inline stylesheet with its critical'd counterpart
  860. if (!styleInlinedCompletely) {
  861. style.textContent = sheet;
  862. } // output stats
  863. const percent = sheet.length / before.length * 100 | 0;
  864. this.logger.info('\u001b[32mInlined ' + prettyBytes(sheet.length) + ' (' + percent + '% of original ' + prettyBytes(before.length) + ') of ' + name + afterText + '.\u001b[39m');
  865. }
  866. }
  867. module.exports = Critters;