我想使用 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 注入当前页面。我的问题:
- 有没有一种方法可以将 Google AJAX 库 API / jQuery 注入页面而不管 onload/onready 状态如何?