使用Google AJAX Libraries API时,将jQuery注入页面失败

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

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

;((function(){ // Call this function once jQuery is available var func = function() { jQuery("body").prepend('
jQuery Rocks!
'); }; // 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 :

   This is my page   

This is my page.

在Firefox 3中,我收到以下错误:

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

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

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

如果您正在注入,则在不使用Google加载器的情况下请求脚本可能更容易:

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

在我们找到不同的解决方案后,我发现了这篇文章。 所以出于某种原因,如果你不能使用已接受的解决方案,这个似乎工作正常:

   

接受的解决方案的一个问题是,您被迫将要在页面上运行的所有代码放入回调函数中。 所以需要从该函数调用任何需要jQuery(如插件)的东西。 并且,所有其他包含需要jQuery的JS文件依赖于在所有其他脚本触发之前加载jQuery。

我有工作!!!!! 我通过查看应用程序操场看出来….

这是开始使用jquery的包装器….在函数中放置一个警告以查看它是否有效

 google.load("jquery", "1.4.2"); function OnLoad(){ $(function(){ }); } google.setOnLoadCallback(OnLoad); 

您可以使用较少痛苦的解决方案将jquery(最新的稳定版本)注入任何页面。

jQuerify – Chrome扩展程序用于将jQuery(最新的稳定版本)注入任何网页(甚至是HTTPS)

Interesting Posts