[英]Injecting jQuery into a page fails when using Google AJAX Libraries API
我想使用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('<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 Libraries API,因為我見過其他人使用jQuery bookmarklet將jQuery注入當前頁面。 我的問題:
如果您正在注入,則可以更輕松地在不使用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 );
})()
在我們找到不同的解決方案后,我發現了這篇文章。 所以出於某種原因,如果你不能使用已接受的解決方案,這個似乎工作得很好:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
// jQuery hasn't been loaded... so let's write it into the head immediately.
document.write('<script type="text/javascript" src="/jquery-1.3.2.min.js"><\/script>')
}
</script>
接受的解決方案的一個問題是,您被迫將要在頁面上運行的所有代碼放入回調函數中。 所以需要從該函數調用任何需要jQuery(如插件)的東西。 並且,所有其他包含需要jQuery的JS文件依賴於在所有其他腳本觸發之前加載jQuery。
您可以使用較少痛苦的解決方案將jquery(最新的穩定版本)注入任何頁面。
jQuerify - Chrome擴展程序用於將jQuery(最新的穩定版本)注入任何網頁(甚至是HTTPS)
我有工作!!!!! 我通過查看應用程序操場看出來....
這是開始使用jquery的包裝器....在函數中放置一個警報以查看它是否有效
google.load("jquery", "1.4.2");
function OnLoad(){
$(function(){
});
}
google.setOnLoadCallback(OnLoad);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.