We recently converted webmail’s javascript handling to an on-demand system to allow for faster login experience. The trickiest part about this was figuring out a cross-browser solution for eval’ing downloaded code in a global scope synchronously (Async is fairly easy using setTimeout and such, but that doesn’t work for us).
Google got me pretty far, with the exception of Safari. I found a few examples that dynamically created a script tag and put the code on the .text property, but that didn’t do anything when I tried it. So I tried using the .innerHTML property instead, but that gave me parse errors.
Then I got it … use the above approach, but use an eval inside to execute the code.
window.my_code = "var x = 3;" //code being in a variable is important
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.innerHTML = 'eval(window.my_code)';
document.getElementsByTagName('head')[0].appendChild(script_tag)
alert(window.x);
Works like a charm.
Note: This only works in Safari. Firefox runs the eval, but does not wait for it to finish before continuing.