I have seen a lot of suggestions about how one should add code dynamically like so (source):
var myScript = document.createElement(\"script\");
myScript.setA
This is probably one of those debates that changes based upon the browser, and the programmer's own opinion. I wouldn't imagine any significant performance difference between the two approaches unless you're doing this kind of thing many many times (and even then, that'd probably be indicative if a design problem).
Just a side note; code passed to eval()
can be particularly difficult to debug, and can't be cached in the same way that asynchronous loading of JavaScript can:
(function() {
var s = document.createElement('script');
s.async = true; // HTML5
s.type = 'text/javascript';
s.src = 'http://example.com/application.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
// can be added to the body element as well, which may be better.
})();
Note that this is different to your code, in that, this loads a script from the server, instead of writing the Javascript directly into the element. Honestly, I can't imagine why you'd want to do that when you can just load a file remotely instead.