⚠️ Archived Post
This is an archived post from my previous blog (2007-2014). It may contain outdated information, broken links, or deprecated technical content. For current writing, please see the main Writing section.

Ruby Script to Inline JavaScript and CSS

Originally published on January 28, 2009

MySpace requires that OpenSocial applications don’t reference external JavaScript and CSS files in the profile view. Of course from a “I’m a spiffy developer that neatly separates all his files” point of view inlining JavaScript and CSS is a Bad Thing®. From a performance point of view, inlining stuff often makes a lot of sense.

So what are we to do?

Well, I just wrote a small Ruby script that understands inline markers like ###inline=somefile.js in your HTML/OpenSocial/XML/Whatever file. Yes, I could have used ERB or something else, but I felt like writing my own ;-). You just put code like this into your file:

<script type="text/javascript">
###inline=scripts.js
</script>
<style type="text/css">
###inline=styles.css
</style>

Then, assuming that your file is called “template.xml”, running it through inliner.rb like this…

ruby inliner.rb template.xml inlined_output.xml

…will result in one file with both your JavaScript and your CSS files inlined.

Here’s the code:

Oh, and with this little snippet you can even inline binary images:

Enjoy!