【问题标题】:How to load stylesheets asynchronously (with loadCSS)如何异步加载样式表(使用 loadCSS)
【发布时间】:2019-08-18 08:46:28
【问题描述】:

如何使用 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 内)?

【问题讨论】:

    标签: css django-pipeline


    【解决方案1】:

    找到解决办法:

    自定义模板标签

    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'">
    

    【讨论】:

      猜你喜欢
      • 2015-04-08
      • 2019-03-07
      • 2011-07-08
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      相关资源
      最近更新 更多