什么是更好的做法:eval或append脚本? [英] What's the better practice: eval or append script?

查看:164
本文介绍了什么是更好的做法:eval或append脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一些自定义的JavaScript,我从一些AJAX调用得到。我可以做一个 eval 的字符串,或者我可以把它附加到一个脚本 -tag到DOM。哪种方法会更好?

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!\');';

方法1 - 脚本

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

方法2 - 评估

eval(dynamicScript);

什么方法更好,为什么?或者有更好的选择吗?

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

推荐答案

我更喜欢 eval 因为通常比创建脚本标签更快,并附加它(特别是如果你想要使用jQuery创建和插入它。)

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).

旁注(脚本标签的有用应用程序)我还使用脚本标记插入方法:In因为窗口对象被沙盒化,所以Google Chrome的扩展程序,注入脚本标签是在页面范围内运行代码的唯一方法。

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。 jQuery.getScript() 的概念。此方法可能很有用。

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

这篇关于什么是更好的做法:eval或append脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆