4

I want to add (append) 3 CSS rules to my head tag using <link /> tags

$('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

$('head').append('<style>.rule0 {} .rule1 {} .rule2 {}</style>');
William Barbosa
  • 4,936
  • 2
  • 19
  • 37
  • [There you go](http://stackoverflow.com/questions/12093509/jquery-add-css-to-head) – William Barbosa May 22 '14 at 13:26
  • You didn't get my question, I don't want to load the my CSS from a location, plus this is an UX question –  May 22 '14 at 13:29
  • 2
    you could `document.createElement('style')` and populate its content (with the styles) then append it. Otherwise, I _believe_ you can do what you're after, but it'd be more like `data:text/css;base64,....` and base64 encode it to avoid spaces and other data. – Brad Christie May 22 '14 at 13:30

1 Answers1

1

It appears you can as long as you properly declare the data 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. So, your .href becomes:

// 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);
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • +1 for the `base64` encode, and I found this tool which uses PHP to encode a string into base64 http://www.base64encode.org/ which came handy –  May 22 '14 at 13:42
  • @AnnaSkylar: keep in mind, the biggest pitfalls with using a data URI is you lose caching. Every visit sends the complete payload, so if you use it on a popular page you'll always have that overhead. But, if you're comfortable with that then it's fine with me. ;-) – Brad Christie May 22 '14 at 13:48
  • it's only 3 rules of CSS and the `.css` is 0.19 KB, it won't cause problems for slow connections –  May 22 '14 at 13:53