Search code examples
javascriptjquerydynamicgoogle-translate

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.


Solution

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