I’m developing a third party script. I’m adding my own stylesheet to the page where the script is embedded. Currently the style is a long string in JavaScript. That’s silly, but it’s faster than appending a style link and making another http request.
Looking at the facebook SDK we see a php script that does something like this, with JS_FILES and CSS_FILES being arrays of file names:
// all.js
foreach ($JS_FILES as $file) {
echo file_get_contents($file);
}
$css = '';
foreach ($CSS_FILES as $file) {
$css .= file_get_contents($file);
}
// css URLs are relative to facebook domains
$css = preg_replace('#url\(/#', 'url(http://static.ak.fbcdn.net/', $css);
echo 'FB.Dom.addCssRules(' . json_encode($css) . ', ["pkg"])';
So the css is converted to JSON and sent to the FB.Dom.addCssRules function which appends the style to the page.
Writing css in JS strings is stupid. I want to utilize SCSS in my style, I want to have syntax highlighting and I want to develop in a reasonable environment.
What do I need to do, how to I hook into the Asset Pipeline / Sprockets / Tilt to make this thing happen?
Code examples are a big plus, as I’m not a crazy good ruby dev.
Edit: I went through the Asset Pipeline docs and didn’t see any way to actually hook into it. The only option I see is to create a Tranfsorm class that calls the default transform and then converts the output to a JS string and sends it to a function. I don’t really know how to do that. I don’t know if I can even require a .jscss files without making the pipeline freak out. Another option (which is quite similar) is to write a gem like Black Coffee, again I don’t really have an idea how should I go about implementing this.
I think @rossta has put you on the right track here. I would suggest a couple of modifications, though. First, if you are writing your stylesheets in sass, and would like the compiled css to be inserted in your javascript, the following would be one way to achieve that:
where
inline.css.scssis somewhere on the assets search path. The methodfind_assetwill compile your sass and return the output as a string. One issue is that the javascript in which you include this won’t be re-compiled unless the javascript file itself changes, or you explicitly markinline.cssas a dependency. You can do this by including the directive