alexmcfarlane
alexmcfarlane

Reputation: 1148

How To Load Critical CSS on Laravel Vapor

PHP: 8.0.2
Laravel: 9.19

We are using 'laravel-mix-criticalcss' to generate our critical CSS. But as we are using Laravel Vapor when we deploy the website the CSS assets are automatically uploaded to S3. How is it best to load the critical CSS into the header?

We considered trying to generate the critical CSS as blade templates (index.css.blade.php) within /resources folder but 'laravel-mix-criticalcss' doesn't seem to allow you to customise the output filenames. We also considered the same solution by copying the files using Mix, but, again it doesn't seem possible to amend the filenames.

We also considered loading the files from S3, but I'd imagine this is very slow.

Another consideration, is loading the CSS via file_get_contents the optimal solution in general, will this not slow the server and Vapor? is there a more Vapor friendly optimal solution?

header.blade.php:

@if(file_exists('../public/css/index_critical.min.css'))
    <style>{!! file_get_contents('../public/css/index_critical.min.css') !!}</style>
@endif

webpack.mix.js:

mix.postCss('resources/css/app.css', 'public/css', [
        require('tailwindcss'),
    ])
    .criticalCss({
        enabled: mix.inProduction(),
        paths: {
            base: 'http://localhost:8081/',
            templates: 'public/css/',
        },
        urls: [
            {url: '', template: 'index'},
        ],
        options: {
            minify: true,
        },
    })
    .version();

Upvotes: 0

Views: 532

Answers (1)

TEFO
TEFO

Reputation: 1643

Yes you may load the css file, but this isnt an ideal solution, because as you mentioned it slows down you API and make the response size bigger. And for API gatway we have some limitation for request/response size. Best solution is just using webpack(laravel-mix) to set the correct prefix.

Just change the base in paths like document mentioned. https://docs.vapor.build/1.0/projects/deployments.html#code-splitting-dynamic-imports-with-mix

Like:

.criticalCss({
        enabled: mix.inProduction(),
        paths: {
            base: process.env.ASSET_URL + "/"
        }

Upvotes: 1

Related Questions