Problem/Motivation

No matter what page I'm on, the module always chooses default-critical.css, even when page-specific critical CSS files exist (front.css, page.css, path-<bundle>.cssetc).

I also see the test CriticalCssHeadTest failing in a separate vanilla dev site. When I debugged the test by dumping the rendered page outputs within the test, I saw the same thing:

default-critical.css is loaded into the page instead of front.css and node-1.css.

Environment

  • D11
  • PHP8.3
Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

kentr created an issue. See original summary.

kentr’s picture

I think it's actually replacing any found file in CriticalCssProvider.php with whatever comes after that file in the list, even if that is a value of FALSE due to a failed file_get_contents().

Breaking out of the loop when a file is found fixes it:

diff --git a/src/Asset/CriticalCssProvider.php b/src/Asset/CriticalCssProvider.php
index 052b31a..92e40ab 100644
--- a/src/Asset/CriticalCssProvider.php
+++ b/src/Asset/CriticalCssProvider.php
@@ -195,7 +195,10 @@ public function getCriticalCss() {
       }
       else {
         $this->criticalCss = @file_get_contents($this->matchedFilePath);
+        if ($this->criticalCss) {
           $this->criticalCss = trim($this->criticalCss);
+          break;
+        }
       }
     }
kentr’s picture

It appears to also fail for local files when CSS preprocessing is enabled.

In that case, the call to file_get_contents() only occurs if the file is external.

kentr’s picture

Disregard my last comment about preprocessing CSS.

It appears that the blank output I'm getting is because the only content of the test CSS files are comments, which are getting stripped by the optimizer.

kentr’s picture

Status: Active » Needs review

This MR makes the test CriticalCssHeadTest pass, and I verified manually.

Also tested manually with external asset URLs for #3454343: Add support for downloading critical CSS from an URL.

albertosilva’s picture

Status: Needs review » Fixed

Thanks @kentr for the MR!

Merged and new version published.

albertosilva’s picture

Status: Fixed » Closed (fixed)
lomasr’s picture

Hi Alberto Silva,

Could you please confirm whether this patch applies to Drupal 10.3.10 and later versions as well? According to the description, it has been tested on Drupal 11. I’d like to make sure before upgrading the module from 2.0.0 to 2.0.3.