Dan Abramov
Dan Abramov

Reputation: 268265

Looking for an elegant way to load JS and execute it

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.

Upvotes: 3

Views: 294

Answers (3)

xkeshav
xkeshav

Reputation: 54050

HeadJS is made for such use, this is easy and optimized way to include scripts This will helps you sure.

basic Method: ( took 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>

using head.js (took 700 ms)

<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

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28864

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

Upvotes: 5

Ryan Olds
Ryan Olds

Reputation: 4847

Try this:

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

Upvotes: 2

Related Questions