繁体   English   中英

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

[英]Looking for an elegant way to load JS and execute it

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

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

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>

看到测试用例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM