JavaScript:无需操作 DOM 即可动态加载脚本?
如何通过 JavaScript 代码添加外部 JavaScript(-library) 到页面,而不需要:
- 最好操作 DOM
- ,而不使用
Eval
?
这意味着不允许通过 JavaScript 添加 script
标签。
JSLint 告诉我“Eval 是邪恶的”,所以我想看看是否有一个选项。一个能够通过 JSLint 的测试。
请避免使用框架来回答,但是研究 jQuery、ExtJS、Require.js 等如何解决动态脚本加载将会很有趣。
How do I add an external JavaScript(-library) to a page through JavaScript-code without:
- Manipulating the DOM
- Preferably without using
Eval
?
That means adding a script
-tag through JavaScript is not allowed.
JSLint tells me "Eval is Evil", so I'm looking to see if there is an option. One that would pass JSLint.
Please avoid answers using frameworks, but looking into how jQuery, ExtJS, Require.js and the likes solve dynamic script loading would be interesting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非使用像
new Function(String);
这样的东西(这实际上是通过代理eval
,因此在eval
的任何情况下都不是一个选项由于邪恶而被排除),你不能。Except by using something like
new Function(String);
(which is effectivelyeval
by proxy and thus not an option in any circumstance whereeval
is ruled out due to being evil), you can't.我认真地认为你的意图背后没有任何理由。您的问题是关于“动态脚本加载”,因此没有“
eval is bad
”言论。显然,您将加载并执行 ECMAscript 代码,这是使用
eval
的一个非常有效的点。由于这是您声明的目标(执行 javascript 代码),那么使用eval
时您的确切问题是什么?无论您如何执行该代码,它都可能始终是危险的或恶意的。目前还没有可用的“.evalButBeCareful()
”方法。所以我最好的猜测是,您想要加载一些代码而不让用户知道。幸运的是,这是不可能的。也许可以对新手隐藏代码,但如果有人愿意,他总是可以轻松地看到当前站点上加载的内容。
I seriously see no reason behind your intention. Your question is about "dynamic script loading", there is no "
eval is evil
" speech for that reason.You're clearly going to load and execute ECMAscript code, that is a very valid point for using
eval
. Since this is your declared goal (executing javascript code), what is your exact problem in usingeval
? Regardless how you execute that code, it might always be dangerous or malicous. There is no ".evalButBeCareful()
" method available (yet).So my best guess is, that you kind of want to load some piece of code without letting the user know about that. Fortunately, this is impossible. It might be possible to hide code from a novice, but if somebody wants to he always can easily see whats loaded onto the current site.