Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 268
puk Avatar asked Dec 05 '11 01:12

puk


1 Answers

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

enter image description here

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?:

  1. Improper use of eval opens up your code for injection attacks
  2. 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.

like image 194
ThinkingStiff Avatar answered Sep 27 '22 22:09

ThinkingStiff