【问题标题】:Looking for an elegant way to load JS and execute it寻找一种优雅的方式来加载 JS 并执行它
【发布时间】:2011-08-30 04:11:17
【问题描述】:

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

【问题讨论】:

  • 有(见答案),但如果你只是自己把它放在一个函数中,你也只需要写一次。 :)
  • 是的——我的意思是我来自不同的背景 (.NET),所以当有常用方法时,我不想在我的代码中传播自定义函数。

标签: javascript jquery dynamic google-translate


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

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      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

      【讨论】:

      • 我对 jQuery 当前提供的功能很好,但如果我需要更复杂的东西,这是一个很好的补充。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多