css - 如何异步加载样式表(使用 loadCSS)
问题描述
如何使用 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 内)吗?
解决方案
找到了解决方案:
自定义模板标签
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'">
推荐阅读
- github - 有没有办法创建可以一次添加到 github 拉取请求中的审阅者别名?
- memory - CUDA内存不足运行时错误,无论如何要删除pytorch“保留内存”
- python - 检查 Pandas 数据框列中的唯一值并与第二列交叉引用
- docker - OpenShift BuildConfig Docker 策略 spec.output.to.name 使用环境变量进行标记
- postgresql - Ecto - 从 postgresql 数据库中选择一个数组字段
- amazon-web-services - 如果商店用户输入未注册任何输入,则结束 Amazon Connect 调用
- java - 声纳“源文件不应有任何重复的块”规则不区分不同的文字
- c - scanf( ) != EOF,脚本仍在等待进一步的输入
- c# - 远程服务器返回错误:(403) Forbidden - C#
- android - 使用导航抽屉或工具栏菜单动画片段过渡