包括< script>在内是否有性能提升?标签而不是使用eval? [英] Is there a performance gain in including <script> tags as opposed to using eval?
问题描述
我已经看到很多关于如何动态添加代码的建议用于动态加载脚本。
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.
No, there is no performance gain using <script>
tags as opposed to using eval
. In the two samples you gave, eval
is much faster in all browsers I tested. Part of the difference is that with <script>
, in addition to running the script, it's modifying the DOM, but that's not all of it. With longer scripts, the difference is not as pronounced, but eval
is still faster:
UPDATE: I updated the demo to better match the tests head-to-head (both are now creating script
blocks). The results still show eval
much faster.
jsPerf: http://jsperf.com/stackoverflow-8380204-eval-vs-script
Thus, the reasons not to use eval
are security-related only. From the accepted answer on Why is using the JavaScript eval function a bad idea?:
- Improper use of eval opens up your code for injection attacks
- Debugging can be more challenging (no line numbers, etc.)
There is a third one that talks about speed, but it is refuted in the comments of that answer. If you can't guarantee the source of the scripts you plan to eval
, it should be avoided.
As an aside: Based on your usage pattern at the end of your question, you might want to check out require.js for dynamically loading scripts.
这篇关于包括< script>在内是否有性能提升?标签而不是使用eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!