Conditional Javascript Includes

javascript

Mon Dec 03 16:46:00 -0800 2007

The Heroku toolbar floats on top of your app, providing access to some development functions.

There’s quite a bit of magic to goes on to make this happen, some of which I might get into another time. But one thing we ran into recently was the matter of conditional javascript includes. We want to use Prototype and the effects libraries for the toolbar (and particularly for some of the upcoming features which will be visually complex). But since our html is being mixed in with the html from the user’s app, and the user may or may not include Prototype and friends, we need a way to conditionally include these files.

There isn’t a best practices sort of way to do this that I can see. But we did come up with a workable solution. Here’s a static HTML proof of concept:

<html><body>

<!-- try commenting out the following line -->
<script src="prototype.js" type="text/javascript"></script>

<script type="text/javascript">
  if (!window.Prototype)
  {
    document.write('<script src="prototype.js" type="text/javascript"><\/script>')
  }
</script>

<div id="write_me"></div>

<script type="text/javascript">
  $('write_me').innerHTML = "prototype is loaded"
</script>

</body></html>

The key here is window.Prototype. “if (Prototype)” will cause an uncatchable exception if Prototype is not defined. But since javascript globals are actually properties of the window object, we can check it there. Javascript doesn’t complain at all on an access to an undefined object property.

There are some problems with this, such as the possibility of differing versions of Prototype in what the user’s app has included and what the toolbar code expects. My biggest complaint with it is that it’s just not that elegant. If anyone has other suggestions I’d be interested to hear them.