如何异步加载样式表(使用loadCSS)

时间:2019-03-27 17:17:14

标签: css django-pipeline

如何使用loadCSS(https://github.com/filamentgroup/loadCSS)加载样式表?

当前,我将loadCSS的javascript和类似的模板标签包含在我的脑海中。我只是用noscript标记将默认的CSS括起来作为备用(如文档中所述)。

<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 :(得分:0)

找到了解决方案:

自定义模板标签

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)

/pipeline/loadcss.html

<link rel="preload" href="{{ url }}" as="style" onload="this.onload=null;this.rel='stylesheet'">