我正在创建一个需要jquery和jquery ui的bookmarklet,并且无法使用健壮/灵活的版本(已经拖拽了SO和各种博客),但他们似乎只检查一个文件已加载(例如jQuery)或只是加载jQuery和其他文件按顺序排列,而不检查它们是否先加载。
我真的很喜欢这个:
(function(){
// the minimum version of jQuery we want
var v = "1.8.2";
// check prior inclusion and version
if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
var done = false;
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
initMyBookmarklet();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
} else {
initMyBookmarklet();
}
function initMyBookmarklet() {
(window.myBookmarklet = function() {
$('body').append('hello world');
})();
}
})();
为jQuery设置最低版本,仅在需要时加载。但是我如何用jQuery UI包装呢?例如设置最小版本,只在需要时加载它并确保它们以正确的顺序加载。
任何指针都会非常感激,
答案 0 :(得分:0)
你走在正确的轨道上...加载jquery后再次检查jquery ui
(function(){
var addScript = function (path, callback) {
var done = false;
var script = document.createElement("script");
script.src = path;
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (callback) {
callback ();
}
}
};
document.getElementsByTagName("head")[0].appendChild(script);
};
var initMyBookmarklet = function () {
(window.myBookmarklet = function() {
$('body').append('hello world');
})();
}
var checkForJQueryUI = function () {
if (condition for jquery ui) {
addScript("http://jquery-ui-path-goes-here/file.js", initMyBookmarklet);
} else {
initMyBookmarklet();
}
};
var checkForJQuery = function () {
// the minimum version of jQuery we want
var v = "1.8.2";
// check prior inclusion and version
if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
addScript("http://ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js", checkForJQueryUI);
} else {
checkForJQueryUI();
}
};
checkForJQuery();
})();