Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the better practice: eval or append script?

Tags:

I need to execute a custom piece of JavaScript I got from some AJAX call. I could do an eval of the string or I could just append it in a script-tag to the DOM. Which method would be better?

var dynamicScript = 'alert(\'Hello world!\');'; 

Method 1 - Script:

var x = '<script type="text/javascript">' + dynamicScript  +'</scr' + 'ipt>'; $(document.body).append(x); 

Method 2 - Eval:

eval(dynamicScript); 

What method is better and why? Or is there an ever better alternative?

like image 333
Kees C. Bakker Avatar asked Feb 03 '12 13:02

Kees C. Bakker


2 Answers

I prefer eval, because it's generally faster than creating a script tag, and appending it (especially if you wanted to create and insert it using jQuery).

Side note (useful application of a script tag) I also use the script-tag-insertion method: In Google Chrome's extensions, injecting script-tags is the only way to run code in the scope of a page, because the window object is sandboxed.

PS. Notion of jQuery.getScript(). This method might be useful.

like image 79
Rob W Avatar answered Sep 19 '22 12:09

Rob W


Neither method is really that good for what you're doing. Your AJAX call should be returning data not serialized scripts. Both of your methods open you up to script injection.

eval should be avioded at all costs. It's slow and dangerous, eval is evil

like image 24
JaredMcAteer Avatar answered Sep 20 '22 12:09

JaredMcAteer