Include a JavaScript Source File into Google’s CodeRunner or OpenSocialDevApp

OpenSocialDevApp or Google’s CodeRunner is a great tool for testing code snippets using OpenSocial API. It allows you to easily test code by cutting and pasting your JavaScript code into a textbox. You don’t need to load a gadget XML file into the server to test out something which can be a tedious process.

This works out really well when your code is small. However, once your code gets bigger, cutting and pasting starts to get painful. Wouldn’t it be nice if you can simply save your JavaScript code into a file, say mytestcode.js, and then just cut and paste a neat single line into the textbox like this?

<script type="text/javascript" 

To test changes in mytestcode.js, all you need to do is re-execute CodeRunner every time you make an update to the file. No need for cutting-and-pasting.

However, this OpenSocial application only accepts raw JavaScript code, so the code above won’t work since it’s an HTML code.

To fix this problem, what we need is a way to convert the HTML code above into a JavaScript code. This is where the technique of dynamically including a JavaScript file comes to the rescue.

The code below is the script-src-tag converted into a JavaScript code. If you are not familiar with this technique, see this posting for details.

function includeJavascript(src) {
  if (document.createElement && document.getElementsByTagName) {
    var head_tag = document.getElementsByTagName('head')[0];
    var script_tag = document.createElement('script');
    script_tag.setAttribute('type', 'text/javascript');
    script_tag.setAttribute('src', src);

Instead of cutting-and-pasting the entire mytestcode.js into the CodeRunner’s textbox, just use the code above and make your changes directly to the mytestcode.js file on your server.

Furthermore, you don’t need to put all your code in a single file. You can break them up into multiple files and call out the include function for each.


With this technique, you can even run your entire OpenSocial application in CoderRunner!

Alvin Abad


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s