I have seen a lot of suggestions about how one should add code dynamically like so (source):
var myScript = document.createElement("script");
myScript.setAttribute("type","text/javascript");
myScript.innerHTML += 'alert("Hello");';
document.body.appendChild(myScript);
As opposed to eval
like so
eval('alert("Hello");');
People complain about performance drops and security issues with eval
, but I can't imagine how adding <script>
tags would be any faster or any more secure.
EDIT people would like to know why I am evaling something as trivial as alert("Hello")
, here is why:
I have a database of, lets say, 1,000,000,000,000 scripts =P obviously I can't load every one, instead the user can load whichever they wish. The scripts are stored serverside in arbritrary locations. Currently I request (xmlhttprequest interpreted as javascript) a script via its script name and the server will find it (somehow) and return it as text, which immediately gets executed/interpreted. I want to know if it would be better to return the script as text, then create a <script>
tag out of it.
Also, this is NOT a duplicate of Javascript difference between eval() and appending script tags, that deals with the functional differences, here I want the performance and security differences.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…