Module always chooses default-critical.css

Created on 4 November 2024, 6 months ago

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
šŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

šŸ‡ŗšŸ‡øUnited States kentr Durango, CO

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @kentr
  • šŸ‡ŗšŸ‡øUnited States kentr Durango, CO

    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;
    +        }
           }
         }
    
  • šŸ‡ŗšŸ‡øUnited States kentr Durango, CO

    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.

  • šŸ‡ŗšŸ‡øUnited States kentr Durango, CO

    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.

  • šŸ‡ŗšŸ‡øUnited States kentr Durango, CO

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

    Also tested manually with external asset URLs for ✨ Add support for downloading critical CSS from an URL Active .

  • šŸ‡ŖšŸ‡øSpain albertosilva Basque Country

    Thanks @kentr for the MR!

    Merged and new version published.

  • šŸ‡ŖšŸ‡øSpain albertosilva Basque Country
  • Status changed to Fixed 3 months ago
  • šŸ‡®šŸ‡³India lomasr

    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.

Production build 0.71.5 2024