Evaluating Script Tags Dynamically
First, a disclaimer: dynamically evaluating scripts is not recommended! Indeed, if your application requires the usage of this script, chances are you're doing it wrong. The separation of design and logic likely hasn't been properly enforced if you're using this method. It's just an awkward use-case that should be avoided. That said, here it is…
Many JavaScript libraries support the evaluating of data returned via XHR. Some, like YUI, do not (yet). In other cases, folks have rolled their own "AJAX library" but still want this behavior. The below script supports searching HTML for scripts and evaluating them:
You can execute some examples yourself below:
- [Download eval.js] (376 bytes)
- [Download eval-min.js] (214 bytes; compressed)
Update 9/28/08: Fixed a bug thanks to Isaac Schlueter (see comments).
This bit: ([^<]*) will fall down on stuff like this:
if (3 < 2) alert(”number line fail!”);
To get around that, you can use a chomping algorithm that cuts off just the bits you need, and evals them as you go.
var evalHTML = function (content) {
alert("YOURE DOING IT WRONG!!");
var split = content.split(/<script/);
split.shift(); // throw away anything before the first script tag
for ( var i = 0, l = split.length; i ...</script>...'
piece = piece.split(/>/);
piece.shift(); // throw it away the 'type="text/javascript"'
var ex;
try {
eval(piece.join('>').split('</script>').shift());
} catch (ex) {}
}
return "I hope you're ashamed of yourself.";
};
Whoops, it borked the script sample in the comment.
Here you go: http://foohack.com/tests/evalhtml.js
FYI: If you wrap your script nodes in tags, you can write and all day long
FYI: If you wrap your script nodes in <![CDATA[ & ]]> tags, you can write <script> and <\/script> all day long
@Isaac: Licking my chops again! I probably should have read how some libraries do this, but I wanted to do it myself from scratch. Thanks for catching that bug.
@fearphage: Not sure what you mean…