Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript difference between eval() and appending script tags

I was wondering if someone could explain the difference between using Javascript's eval(), and another approach, like using JQuery to create script tags and then appending that element to the page:

eval(somecode);

vs.

$("<script type='text/javascript'>"+somecode+"</script>").appendTo("head");

Not sure if this is relevant, but here's the context: I'm working with a version of the Drupal Popups module whose basic purpose is to easily turn regular links into popups by AJAX'ing an entire page request and appending it to the page in a modal window. This frequently includes external CSS and Javascript files. In an effort to improve the performance of all this AJAX loading I switched over to use AJAX queueing, and I changed an eval() of external scripts into the alternative listed about. However, that caused sporadic Javscript bugs on various other pages.

like image 427
Oliver Avatar asked Feb 04 '11 23:02

Oliver


2 Answers

Well one (as far as differences go) is eval will return the result of an expression.

var result = eval('3+4'); // result = 7 

As long as your javascript string is in the structure of a script block, i would suggest injecting it within a script tag/

like image 125
Josiah Ruddell Avatar answered Sep 23 '22 20:09

Josiah Ruddell


Adding script tags will load the scripts synchronously, whereas loading when you eval text via XHR, that was loaded asynchronously. Because of the async, the scripts were probably loaded out of order.

Note there are a billion if-but-then cases to this, but I'm guessing this is the case based on your scenario.

Now, you could load the XHR synchronously, but then things will drastically slow down. Browsers can load six (ish) scripts at once but execute them in order. The XHR will load one at a time.

like image 36
mwilcox Avatar answered Sep 23 '22 20:09

mwilcox