Injecting jQuery into a page fails when using Google AJAX Libraries API

Posted by jakemcgraw on Stack Overflow See other posts from Stack Overflow or by jakemcgraw
Published on 2009-05-08T15:01:06Z Indexed on 2010/05/18 4:10 UTC
Read the original article Hit count: 312

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:

;((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:

<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>

In Firefox 3 I get the following error:

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

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:

  • Is there a method for injecting the Google AJAX Libraries API / jQuery into a page regardless of the onload/onready state?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript