SXA Preoptimized Theme Assets - You're Still Using and Generating Optimized Files

SXA 9.3 introduced the ability to pre-optimize your JS/CSS theme assets. Before Sitecore 9.3, SXA would minify and bundle theme assets on the first request to a theme with optimization enabled. However, even if you're using SXA's pre-optimization system the old system is still alive and well; in my case it was even causing a subtle styling issue -- you may be experiencing hard to track down (or even discover) front-end issues as well!

The culprit is the processor Sitecore.XA.Foundation.Theming.Pipelines.MediaRequestHandler.OptimizedFiles located in Sitecore.XA.Foundation.Theming.dll. This processor is responsible for handling requests for optimized JS or CSS files.

The logic for this processor is supposed to be the following:

  • Check if a media request is for "optimized" or "optimized-min" .js, .css files
  • Find the appropriate file under the theme in the database
  • Generate the "optimized" or "optimized-min" file

Now it's important to note that the first request to page will actually correctly render out the pre-optimized-min path to the end user, and that is the exact file that will be return. But since the first request causes the creation of "bad" optimized-min file and sitecore sorts returned items alphabetically with the sitecore query [...].

The code below only contains the lines relevant to this issue, other code has been removed.

items.Where(new Func(this.CanProcess)).ForEach((Action) (item =>
    string content = this.GetMediaItemContent((MediaItem) item);
    if (minify && !item.InheritsFrom(Sitecore.XA.Foundation.Theming.Templates.UnminifiedFile.ID))
        content = this.MinifyContent(content, type);

protected virtual bool CanProcess(Item item) => !item.Name.Is("optimized") && !item.Name.Is("optimized-min");

Since CanProcess returns false for the pre-optimized-min file being requested (it does not exactly match either "optimized" or "optimized-min"), and the "pre-optimized-file" does not inherit from the unminified template, sitecore proceeds to minify our already pre-minified file!

AFter the newly "optimized-"min" CSS or JS file is generated, the processor responsible for serving up the files will return the optimized-min file for all subsequent requests.

Was this post any good?
This post was not helpful
This post was not helpful
This post was not helpful