Как загружать таблицы стилей асинхронно (с помощью loadCSS) - PullRequest
0 голосов
/ 27 марта 2019

как я могу загрузить свои таблицы стилей с помощью loadCSS (https://github.com/filamentgroup/loadCSS)?

В настоящее время я включаю javascript loadCSS с таким тегом шаблона в мою голову. Я просто окружил свой css по умолчанию тегами noscript как запасной вариант (как описано в документации).

<head>        
    ...
    <noscript>
        {% stylesheet "main" %}
    </noscript>

    ...
    <script>
        {% include "components/loadCSS.js" %}
    </script>
    ...
</head>

Но как я могу создать такой вывод?

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

Могу ли я как-то получить ссылки (в пределах href) в моем шаблоне?

1 Ответ

0 голосов
/ 27 марта 2019

Нашли решение:

Пользовательский шаблон тега

from django import template
from pipeline.templatetags.pipeline import StylesheetNode
from pipeline.utils import guess_type
from django.utils.safestring import mark_safe
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template.loader import render_to_string
register = template.Library()

class MyStylesheetNode(StylesheetNode):

    def render_css(self, package, path):
        template_name = "pipeline/loadcss.html"
        context = package.extra_context
        context.update({
            'type': guess_type(path, 'text/css'),
            'url': mark_safe(staticfiles_storage.url(path))
        })
        return render_to_string(template_name, context)

@register.tag
def mytest(parser, token):
    try:
        tag_name, name = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            '%r requires exactly one argument: the name of a group in the PIPELINE.JAVASVRIPT setting' %
            token.split_contents()[0])
    return MyStylesheetNode(name)

/ трубопровод / loadcss.html

<link rel="preload" href="{{ url }}" as="style" onload="this.onload=null;this.rel='stylesheet'">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...