Adding javascript to Blogger posts

First off: Blogger does not let you post <script> tags to your blog. (Edit: It does, at least in non-beta, though it warns you about doing so, probably assuming it wasn't done intentionally.) Which is annoying, but perhaps a design choice to prevent code from executing outside of the context of the blog when syndicated through the blog's Atom feed. Or just plain imposing "this should not be in a blog" opinions on bloggers. Whichever.

I'm a bit surprised, though, as we can still use onclick handlers and the like, which I have put to good use once in a while in previous articles to make small in-page utilities and more helpful self-configurable tutorials. Anyway, we can fortunately put javascript code in our blog templates, so for most purposes there are ways of getting around this small annoyance.

A while ago, I was experimenting with posting plain javascript code in Blogger posts with a template that would let external pages include the result as script tags. Not a unique thought, apparently, as Stephane Hamel has institutionalized the practice. And quite cleverly too, using the year part of the post date (minus 2000) for script major version, month number for minors, and page title for script name. Version 1.1 of the Hello World example, thus maps to http://code67.blogspot.com/2001/01/hello-world.html.

The scheme doesn't allow for .0 minors, though; I would have gone for subtracting one from the month number had I devised the system. (Maybe Stephane likes RCS revision numbers, starting at 1.1. ;-)

If you want to do a less elaborate version for inlining code in a blog post, and just want to put the code in the post you are currently writing, rather than pulling it in from an external URL, I would suggest another solution though. Put this block in your blog template:
<script type="text/javascript">
var c = document.getElementsByTagName('code'), s, i;
var junk = /^\s*\46lt;\133\133CDATA\133|]]\46gt;\s*$/g;
for( i=0; i<c.length; i++ )
s = c[i].getAttribute('style') || '';
if( s.match( /display[\s:]+none/i ) )
eval( c[i].innerHTML.replace( junk, '' ) );
(ideally in some function run when the onload event has fired) and it will let you use a <code style="display:none"> <[[CDATA[ your javascript code here ]]></code> sections as if they were really <script type="text/javascrtipt"> //<[[CDATA[ your javascript code here //]]></script> tags. They will of course not show up visibly in your feed, nor do any harm there, either.

Happy hacking!
blog comments powered by Disqus