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

我怕爱的太早我们不能终老 提交于 2019-11-28 23:12:18

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.

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

If the ajax call is returning html with script tags, you can use $.load() to import the script.

http://api.jquery.com/load/

Add it to the DOM. Reasons (taken from http://ajaxpatterns.org/On-Demand_Javascript ):

The JavaScript will automatically be evaluated in much the same way as JavaScript linked in the static HTML is evaluated when the tag is first encountered. You can declare a bare function or variable without adding it to the window.

You can load JavaScript from external domains.

The URL points to a specific Javascript resource. With XMLHttpRequest, there's more flexibility: you can, for example, send several JavaScript snippets inside different XML nodes.

The DOM is affected in a different way. Even if the behaviour is transient, the script will be added to the DOM, whereas it would disappear after an XMLHttpRequest callback eval'd it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!