寻找一种加载JS并执行它的优雅方式

时间:2011-05-21 09:58:02

标签: javascript jquery dynamic google-translate

我是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中是否有任何单行代码。

3 个答案:

答案 0 :(得分:5)

$.getScript('https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + $('#sourceText').html());

答案 1 :(得分:2)

答案 2 :(得分:1)

HeadJS 是为此类用途而设计的,这是一种简单且优化的方式来包含脚本这将有助于您确定。

基本方法:(耗时800ms)

<script src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js"></script>
<script src="https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js"></script>
<script src="https://github.com/smith/scripty2/raw/master/lib/prototype.js"></script>

<script src="https://github.com/headjs/www/raw/master/content/test/jquery-ui.js"></script>
<script src="https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js"></script>

使用head.js(耗时700毫秒)

<script src="../media/js/head.min.js"></script>

<script>
head.js("https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js")
     .js("https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js")
     .js("https://github.com/smith/scripty2/raw/master/lib/prototype.js")
     .js("https://github.com/headjs/www/raw/master/content/test/jquery-ui.js")
     .js("https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js");
</script>

<强> see the testcase