Search code examples
jquerycsshtmluser-experiencedata-uri

Is it valid to use data:text/css?


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>');

Solution

  • 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);