How can I defer or preload the CSS without other elements popping up quickly while page loads or blocking the first paint of of the website? Please tell if I am doing something wrong here. Thanks in advance!
I would assume your theme.css is critical (as in it affects the critical rendering path). If so, you should not be deferring it since that only further delays the render of your page. Instead, you should make sure it’s prioritized by either inlining it in the HTML (turn it into a Liquid snippet and render it) or at the very least, add a preload hint at the very top of the HTML so the browser sees it immediately as the HTML is streamed to it.
One drawback to note regarding inlining is that if your CSS file is pretty large, the browser will have to re-download it each time if its inlined, which will be a worse UX compared to having the browser cache the file and load it from cache on subsequent requests. You can either conditionally inline the CSS depending if the browser has already downloaded it (difficult to do, but I’ve done it before) or just preload the CSS as early as possible as I mentioned in the previous paragraph.
If the CSS is not critical, then you should asynchronously load it like this:
Hi @Eddie-Hosseini , in this thread I’m explaining how to do a specific web performance optimization, but it’s not necessarily the best for your site. I’d be happy to help with your site, but since it might not be relevant for others in this thread, I would recommend messaging me directly or email me via jamesk (at) devisedlabs.com.
Just chipping in with something that might be useful. I’ve had to do this recently while developing a theme and found it quite frustrating having to manually generate the critical-css and upload it to the theme files. I also noticed my css was widely different between some pages (product page vs home page). So I built an app to solve these problems.
Check it out here.
It will generate all the critical css for every type of page on your store (home page, product pages, collections, pages, blogs, etc. You still need to click the button every time your theme’s css changes, but I’m thinking about a webhook to do it automatically in the future.