Ищете элегантный способ загрузить JS и выполнить его - PullRequest
3 голосов
/ 21 мая 2011

Я новичок в 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 ]

5 голосов
/ 21 мая 2011
2 голосов
/ 21 мая 2011

Попробуйте это:

http://api.jquery.com/jQuery.getScript/

1 голос
/ 21 мая 2011

HeadJS создан для такого использования, это простой и оптимизированный способ включения скриптов. Это поможет вам уверенно.

основной метод: (потребовалось 800 мс)

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

см. Контрольный пример

...