# Asynchronous CSS Loading in Sage

**URL:** https://discourse.roots.io/t/asynchronous-css-loading-in-sage/14108
**Category:** sage
**Tags:** guide
**Created:** 2018-11-12T17:35:54Z
**Posts:** 30
**Showing post:** 14 of 30

## Post 14 by @codepuncher — 2019-07-10T15:31:42Z

I’ve rewritten it a little bit to use the local files instead of requesting remote files (also using WP\_Filesystem), this may be of use.

This is the main code:

```
# app/filters.php
add_filter('style_loader_tag', function (string $html, string $handle): string {
    if ('development' === WP_ENV || is_admin() || ! is_front_page()) {
        return $html;
    }

    $dom = new \DOMDocument();
    $dom->loadHTML($html);
    $tag = $dom->getElementById("{$handle}-css");
    $tag->setAttribute('rel', 'preload');
    $tag->setAttribute('as', 'style');
    // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
    $tag->setAttribute('onload', "this.onload=null;this.rel='stylesheet'");
    $tag->removeAttribute('type');
    $html = $dom->saveHTML($tag);
    return $html;
}, 999, 3);
add_action('wp_head', function (): void {
    /** @var \WP_Filesystem_Base */
    global $wp_filesystem;

    if ('development' === WP_ENV || ! is_front_page()) {
        return;
    }

    if (empty($wp_filesystem)) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
    }

    \WP_Filesystem();

    $preload_script = get_theme_file_path() . '/resources/assets/scripts/cssrelpreload.js';

    if ($wp_filesystem->is_readable($preload_script)) {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo '<script id="critical-js">' . $wp_filesystem->get_contents($preload_script) . '</script>';
    }
}, 101);

add_action('wp_head', function (): void {
    if ('development' === WP_ENV || ! is_front_page()) {
        return;
    }

    /** @var \WP_Filesystem_Base */
    global $wp_filesystem;

    if (empty($wp_filesystem)) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
    }

    \WP_Filesystem();

    $critical_CSS = asset_file_path('styles/critical-home.css');

    if ($wp_filesystem->is_readable($critical_CSS)) {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo '<style id="critical-css">' . $wp_filesystem->get_contents($critical_CSS) . '</style>';
    }
}, 1);
```

This code is for `assets_file_path()` which is used above.

```
# config/assets.php
    'path' => get_theme_file_path().'/dist',
```

```
# app/helpers.php
function asset_file_path(string $asset): string
{
    return config('assets.path') . '/' . sage('assets')->get($asset);
}
```

Read more of the above here: [SVG sprites workflow](https://discourse.roots.io/t/svg-sprites-workflow/10903/12)

---

_[View the full topic](https://discourse.roots.io/t/asynchronous-css-loading-in-sage/14108)._
