寻找一种优雅的方式来加载 JS 并执行它
我是 JavaScript 新手,我真的很喜欢 jQuery,并且讨厌编写一些繁琐的代码来完成简单的事情。
我目前正在尝试动态加载外部 JS 并执行它(以与 Google Translate API 进行通信)。
示例代码创建一个 script
标记,设置其 src
并将其附加到文档的 head
来执行它:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
我想知道是否有任何单行代码在 jQuery 中为此。
I'm new into JavaScript and I really like jQuery and hate when it comes to writing some cumbersome code to get simple things done.
I'm currently trying to load an external JS dynamically and execute it (to communicate with Google Translate API).
The sample code creates a script
tag, sets its src
and appends it to document's head
to execute it:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
I wonder if there's any one-liner in jQuery for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
http://api.jquery.com/jQuery.getScript/
Try this:
http://api.jquery.com/jQuery.getScript/
HeadJS 就是为此类用途而设计的,这是包含脚本的简单且优化的方式这将有所帮助你确定。
基本方法:(花了800毫秒)
使用head.js(花了700毫秒)
查看测试用例
HeadJS is made for such use, this is easy and optimized way to include scripts This will helps you sure.
basic Method: ( took 800ms)
using head.js (took 700 ms)
see the testcase