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 ブックマークレットを使用して現在のページに jQuery を挿入するのを見たことがあります。私の質問:
- onload/onready 状態に関係なく、Google AJAX Libraries API / jQuery をページに挿入する方法はありますか?