[英]Is it valid to use data:text/css?
I want to add (append) 3 CSS
rules to my head
tag using <link />
tags 我想使用
<link />
标签向我的head
标签添加(附加)3个CSS
规则
$('head').append('<link rel="stylesheet" href="data:text/css, .rule0 {} .rule1 {} .rule2 {}" />');
Is this syntax valid to use or not? 这种语法有效使用与否?
I know I can wrap my rules within <style>
Like 我知道我可以在
<style>
包含我的规则
$('head').append('<style>.rule0 {} .rule1 {} .rule2 {}</style>');
It appears you can as long as you properly declare the data URI. 只要您正确声明数据URI,它就会出现。 I've found the following to work:
我找到了以下工作:
// Your CSS content, whatever it may be
var css = '*{color:red;}';
// Build your `<link>` dynamically
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'data:text/css;charset=UTF-8,' + encodeURIComponent(css);
// Append to `<head>`
document.getElementsByTagName('head')[0].appendChild(link);
Results in the page text turning red . 页面文本中的结果变为红色 。
Though, depending on how long your CSS it, you may also want to base64 encode it. 虽然,根据你的CSS多长时间,你可能还想对它进行base64编码。 So, your
.href
becomes: 所以,你的
.href
变为:
// note: you need to find a base64_encode implementation for this; javascript
// doesn't natively have one.
link.href = 'data:text/css;base64,' + base64_encode(css);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.