使用Google AJAX Libraries API时,将jQuery注入页面失败 [英] Injecting jQuery into a page fails when using Google AJAX Libraries API

查看:74
本文介绍了使用Google AJAX Libraries API时,将jQuery注入页面失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Google AJAX Libraries API将jQuery注入页面,我提出了以下解决方案:

I'd like to inject jQuery into a page using the Google AJAX Libraries API, I've come up with the following solution:

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

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();
  }
})());

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

The script would then be included in a page on a separate domain:

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

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中,我收到以下错误:

In Firefox 3 I get the following error:

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

该错误似乎特定于Google AJAX Libraries API,因为我'看到其他人使用jQuery bookmarklet将jQuery注入当前页面。我的问题:

The error appears to be specific to the Google AJAX Libraries API, as I've seen others use a jQuery bookmarklet to inject jQuery into the current page. My question:


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

推荐答案

如果你正在注射,在不使用谷歌加载器的情况下请求脚本可能更容易:

If you're injecting, it's probably easier to request the script without using the 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 );
})()

这篇关于使用Google AJAX Libraries API时,将jQuery注入页面失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆