ClojureScript in HTML files

A proof of concept: putting ClojureScript code into an HTML document. What you see here is derived from ClojureScript compiled in ClojureScript, though I am sure that Joel Martin never intended for his code to be used as badly as I have used it. Blame me, not him :)

My thinking was as follows: if his ClojureScript REPL can compile from strings entered into a text area, why can’t it compile from strings that are in an HTML document. I knew that sort of thing was possible; processing-js can do it. In fact, I lifted some of their code and modified it slightly; it's in the load_ext.js file.

I have put this all together without a thorough understanding of the original (as will be obvious when you look at the code). Again, it’s a proof of concept, and, if it turns out to be useful, I leave it to smarter and more skilled people to make it work better. It’s on github.


A: B: Result:

Here’s the script in the <head> of the document. I am including ClojureScript code in the HTML file directly; the file load_ext.js compiles it on the fly. At the moment, you can do only one included .cljs file. I have linked to the external files so you can see them easily.

<script type="text/javascript" src="out/goog/base.js"></script>
<script type="text/javascript" src="dependencies.js"></script>

<script type="text/clojurescript">
(defn avg [a b] (/ (+ a b) 2))
</script>

<script type="text/clojurescript" src="mathstuff.cljs"></script>

<script type="text/clojurescript">
(defn product [a b] (* a b))
(defn getField [fieldname]
  (.-value (.getElementById js/document fieldname)))
</script>

<script type="text/javascript">
  goog.require('cljs.core');
  goog.require('cljs.repl');
  goog.provide('cljs.user');
</script>

<script type="text/javascript" src="load_ext.js"/></script>
<script type="text/javascript">
var a;
var b;

function getVars() {
  a = parseFloat(cljs.user.getField("a"));
  b = parseFloat(cljs.user.getField("b"));
}

function putResult(result) {
  document.getElementById("result").value = result;
}