CSS Tree-shaking

Because of AMP limiting of CSS into a single custom style element and a max of 75KB per page, the AMP_Style_Sanitizer is key in enabling the rendering of AMP pages that do not violate such constraints. The tasks performed include:

  • Collects inline styles and outputs them in the amp-custom stylesheet.  
  • Fetch all external stylesheets (except for whitelisted fonts), collect all style elements in the document, and create style rules from inline style attributes
  • Parse/process the collected styles to ensure that:
    • There are no invalid at-rules and no disallowed CSS properties
    • Relative paths for background images are absolute
    • Any !important qualifier is transformed into style rules with higher-specificity selectors
  • If the result is larger than AMP’s 75KB limit, as CSS tree-shaking algorithm is applied
  • If after tree-shaking there is still more than 75KB, then any stylesheet that takes the total over 75KB will be omitted.
  • The result of the parsed styles is then minified, serialized, and stored in a transient, which are a simple and standardized way in WordPress for storing cached data in the database, temporarily by giving it a custom name and a timeframe after which it will expire and be deleted
  • Construct the style[custom] element to be added to the head