Conditional stylesheet load doesn't work until Refresh of page


I am trying to have a seperate style sheet for a custom page layout load only when that page is requested to improve our performance score according to lighthouse.


I've done this by using the statement in theme.liquid


{% if page.template_suffix == 'kabrita-hcp' %}
{{ 'hcp-page.css' | asset_url | stylesheet_tag }}
{% endif %}


My template is called "page.kabrita-hcp.liquid" which I would assume returns the value "kabrita-hcp" which should return as true in that if statement.


This works only when you refresh after visiting the page. The first visit, the content is unstyled.


I've also tried:


{% if template contains "kabrita-hcp" %}

{{ 'hcp-page.css' | asset_url | stylesheet_tag }}
{% endif %}


That just makes it load on every page.


Really need a solution to improve being able to partition style sheets so we can mitigate being penalized for site performance by search engines.


Preview link:

Problem Solved? ✔️Accept the solution so you can help others.
Confused? Busy? ? I can help! Email:
Buy me a coffee? ☕
Shopify Partner
792 124 390
- make file hcp.css.liquid in asset.
- put all css in that file for hcp page.
- now put condition over all css codes. Like below.
{% if template.suffix == 'kabrita-hcp' %}
All css codes in file here
{% endif %}

- if not works try to change template.suffix condition.
- like and accept my answer as solution.
1 Like
Shopify Expert
700 53 156

If the file is small I wouldn't worry too much. You're not "being penalized", it's just a suggestion from an automated tool.


I usually conditionally load JS when I can. CSS sure if it's a large file but personally I don't bother with files under 10kb.


You could do something like this <h1> {{page.template_suffix }} </h1> on a test theme to have it show what's loading there (or just use html comments if you're testing on live site).

That might give you a clue why it's not loading on the first try. I don't think I've seen an instance where first visit doesn't show it but repeat visits do. Might be some app interference with caching or something, but displaying the variable should help.

Founder of Speed Boostr (Shopify optimization and dev agency).
Creator of Theme Scientist (A/B testing app).
Creator of Order Automator (app that auto tags + fulfills orders, send emails).
Creator of Tip Jar (add a tip button to your store).
Creator of Shopify Analyzer (free performance analysis tool).
My team also builds custom apps and automated solutions.
Enjoy the adventure!