critters icon indicating copy to clipboard operation
critters copied to clipboard

Don't inline print styles

Open developit opened this issue 5 years ago • 2 comments

See preactjs/preact-cli#1188 - <style media="print"> are currently included in critical rules, which should never be the case.

developit avatar Jun 08 '20 20:06 developit

For now, we can do a simple check both here and here, as well as here where we filter the rules:

+ // print styles are not considered critical. everything else is.
+ isCriticalMedia(media) {
+   return !media || !/(?<!not\s)print\b/i.test(media);
+ }

  async embedLinkedStylesheet (link, compilation, outputPath, publicPath) {
    const href = link.getAttribute('href');
    const media = link.getAttribute('media');
    const document = link.ownerDocument;

+   if (!this.isCriticalMedia(media)) return; // ignore print/etc styles

    // ...etc
  }

  async processStyle (style) {
+   const media = style.getAttribute(media);
+   if (!this.isCriticalMedia(media)) return; // ignore print/etc styles

    // ...etc

    // Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
    // This first pass is also used to collect font and keyframe usage used in the second pass.
    walkStyleRules(ast, markOnly(rule => {
      if (rule.type === 'rule') {
        // ...etc
      }

      // keep font and media rules, they're handled in the second pass:
-     if (rule.type === 'font-face') return;
+     if (rule.type === 'font-face' || rule.type === 'media') return;
  }

    // ...etc

    // Second pass, using data picked up from the first
    walkStyleRulesWithReverseMirror(ast, astInverse, rule => {
      // remove any rules marked in the first pass
      if (rule.$$remove === true) return false;

      applyMarkedSelectors(rule);

      // prune @keyframes rules
      if (rule.type === 'keyframes') {
        if (keyframesMode === 'none') return false;
        if (keyframesMode === 'all') return true;
        return criticalKeyframeNames.indexOf(rule.name) !== -1;
      }

+     // prune @media (print) { ... }
+     if (rule.type === 'media') {
+       return this.isCriticalMedia(rule.media);
+     }

developit avatar Jun 09 '20 18:06 developit

Nice tanks

7M0506ALO avatar Feb 23 '21 05:02 7M0506ALO