javascript - 使用 Google AJAX 库 API 时将 jQuery 注入(inject)页面失败

标签 javascript jquery google-ajax-libraries

我想使用 Google AJAX 库 API 将 jQuery 注入(inject)到页面中,我想出了以下解决方案:

http://my-domain.com/inject-jquery.js :

;((function(){

  // Call this function once jQuery is available
  var func = function() {
    jQuery("body").prepend('<div>jQuery Rocks!</div>');
  };

  // Detect if page is already using jQuery
  if (!window.jQuery) {
    var done = false;
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi";
    script.onload = script.onreadystatechange = function(){

      // Once Google AJAX Libraries API is loaded ...
      if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {

        done = true;

        // ... load jQuery ...
        window.google.load("jquery", "1", {callback:function(){

          jQuery.noConflict();

          // ... jQuery available, fire function.
          func();
        }});

        // Prevent IE memory leaking
        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
      }
    }

    // Load Google AJAX Libraries API
    head.appendChild(script);

  // Page already using jQuery, fire function
  } else {
    func();
  }
})());

然后脚本将包含在单独域的页面中:

http://some-other-domain.com/page.html :

<html>
  <head>
    <title>This is my page</title>
  </head>
  <body>
    <h1>This is my page.</h1>
    <script src="http://my-domain.com/inject-jquery.js"></script>
  </body>
</html>

在 Firefox 3 中我得到以下错误:

Module: 'jquery' must be loaded before DOM onLoad! jsapi (line 16)

该错误似乎特定于 Google AJAX 库 API,因为我看到其他人使用 jQuery 书签将 jQuery 注入(inject)当前页面。我的问题:

  • 是否有一种方法可以将 Google AJAX Libraries API/jQuery 注入(inject)到页面中而不管 onload/onready 状态如何?

最佳答案

如果您正在注入(inject),那么在不使用 google loader 的情况下请求脚本可能会更容易:

(function() {
    var script = document.createElement("script");
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
    script.onload = script.onreadystatechange = function(){ /* your callback here */ };
    document.body.appendChild( script );
})()

关于javascript - 使用 Google AJAX 库 API 时将 jQuery 注入(inject)页面失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/840240/

相关文章:

javascript - 无论如何要找出 Facebook 评论何时加载到页面上?

jquery - 适用于 jQuery 的 Google AJAX 库 CDN

javascript - 动态地将表 td 分解为单独的 tr

php - Ajax/jQuery 使用数组填充 Laravel 中的表

javascript - 传单中的标签问题

javascript - 上传完成后如何获取json结果?

javascript - Google Visualization API/注释时间线中 Y 轴的自动重新缩放

jquery - 使用谷歌托管的 jQuery 的最佳方式,但回退到我在谷歌上的托管库失败

javascript - 如何为 marked.js 编写自定义 InlineLexer 规则?

javascript - 替换已弃用的 `keypress` DOM 事件