Inject Javascript from ASLX file

jaynabonne
Here's another bit of esoterica. But if you're using Javascript, it might come in handy.

The attached file has a simple function that allows you to inject Javascript onto the current page from an ASLX file as opposed to having it statically in an associated .js file.

Advantages:
- You can keep your Javascript in the same file as your ASLX code
- You can, if necessary, generate custom Javascript on the fly.
- You can choose to only insert Javascript when you actually need it.

Disadvantages:
If you store your JS in a string attribute on an object (e.g. the game), keep in mind that all newlines are removed, meaning that the entire bit of JS code ends up on a single line. This means:
- You can't have "to end of line" comments (those starting with //) as it will comment out all following code.
- You must terminate all your JS statements with a ";", as there are no line ends to give you the implicit statement end.
- Also, with each ClearScreen, you will most likely need to inject the Javascript again (as you do, for example, with style sheets).

Clearly, if you have large JS libaries, you will want to keep them as .js files. But for small pieces, or if you're doing some experimentation, (or if you're distributing an ASLX library that needs to also include some Javascript), then it might be handy to keep the JS code with your aslx code.

Sample:
(You would need to include InjectJavascript.js in your project)

<game>
...
<js> <![CDATA[
function setText(layer, text) {
var element = document.getElementById(layer)
element.innerHTML=text;
}
]]></js>
</game>


Then at some point, you can simply do:

JS.InjectJavascript(game.js)

to install the function.

Then you can do something like:

JS.setText(layer, "This is new layer text")

to invoke it.

The Javascript code in the attachment is simple:

function InjectJavascript(script) {
var elem = document.createElement("script");
elem.innerHTML = script;
var tag = document.getElementsByTagName("script")[0];
tag.parentNode.insertBefore(elem, tag);
}

Sora574
What's the difference between using this library and using
JS.eval (game.js)
? Or is it basically the same thing?

jaynabonne
I haven't tried the JS.eval approach. Perhaps that's a better way. :)

Sora574
There's several other ways you could do it, too.
For example, to put it straight into the HTML, you could use
JS.eval ("$('head').append('<script type=\"text/javascript\">" + game.js + "</script>');")

This would solve the problem of when you use 'ClearScreen' the scripts go away.

NOTE: I didn't actually test that. I'm just kind of guessing :)

This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums