Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...