getkirby / ideas

This is the backlog of ideas and feature requests from the last two years. Use our new feedback platform to post your new ideas or vote on existing ideas.
https://feedback.getkirby.com
20 stars 0 forks source link

`css()` helper: conditional `rel="preload"` attribute #337

Open grommas opened 5 years ago

grommas commented 5 years ago

Hi there

Would be nice to have the possibility to preload css or js files with the options array of your helper functions. This idea is based on the article Modern Asynchronous CSS Loading from the filament group.

I changed the implementation of the rel attribute in my following example, based on your kirby/config/helpers.php – probably not optimal yet:

function css($url, $options = null)
{
    if (is_array($url) === true) {
        $links = array_map(function ($url) use ($options) {
            return css($url, $options);
        }, $url);
        return implode(PHP_EOL, $links);
    }
    if (is_string($options) === true) {
        $options = ['media' => $options];
    }
    $kirby = App::instance();
    if ($url === '@auto') {
        if (!$url = Url::toTemplateAsset('css/templates', 'css')) {
            return null;
        }
    }
    $url  = $kirby->component('css')($kirby, $url, $options);
    $url  = Url::to($url);
    $rel = in_array('rel', $options) ? 'preload' : 'stylesheet'; // added
    $attr = array_merge((array)$options, [
        'href' => $url,
        'rel'  => $rel // changed from 'stylesheet' to $rel
    ]);
    return '<link ' . attr($attr) . '>';
}
grommas commented 5 years ago

ah, even easier than expected. It works by just swapping the two arrays to merge:

function css($url, $options = null)
{
    if (is_array($url) === true) {
        $links = array_map(function ($url) use ($options) {
            return css($url, $options);
        }, $url);

        return implode(PHP_EOL, $links);
    }

    if (is_string($options) === true) {
        $options = ['media' => $options];
    }

    $kirby = App::instance();

    if ($url === '@auto') {
        if (!$url = Url::toTemplateAsset('css/templates', 'css')) {
            return null;
        }
    }

    $url  = $kirby->component('css')($kirby, $url, $options);
    $url  = Url::to($url);
    $attr = array_merge([
        'href' => $url,
        'rel'  => 'stylesheet'
    ], (array)$options); // swapped arrays

    return '<link ' . attr($attr) . '>';
}