Q:

Use JavaScript to update the contents of a script tag dynamically

This click event works:
document.getElementById('control').addEventListener('click', function(){

   alert('test');

});

Why can't I make it the content of a script tag that already exists on the page?
var s = document.getElementsByTagName("script")[0];
s.innerHTML = "document.getElementById('control').addEventListener('click', function(){alert('test');});";

I've tried enclosing the attempt to do something in an IIFE:
s.innerHTML = "(function(){alert('test')}());";

so that it will call itself.
Also:
s.innerHTML = "var f = function(){alert('f')}; f();"

I'm only interested theoretically and in no way am saying this is a good or bad idea, but how could I make it work?

A:

Script tags are evaluated once and code is not replaced if you change their contents (they work differently than other types of tags in this regard).  If you want to add new code to the page, you can simply add new script tags to the page that contains the new code.  If you want to redefine existing publicly accessible functions, you can simply redefine them with new code.
So, if you want to replace a previous definition of function f(), you can simply assign new code to that symbol:
f = function() {alert("new f");}

You can insert new scripts from a remote source at any time with a code snippet like this:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = url;
document.getElementsByTagName("head")[0].appendChild(s);

It is also possible to use eval() to pass text to the javascript engine that you want it to parse and then run, but there are rarely any good reasons to do it this way as there are generally better ways to solve a problem like this.

