使用以下函数,该脚本询问浏览器是否 <input type="date">
是本地可用的。如果没有,它将从 CDN 加载 jQuery UI。
$(document).ready(function(event){
// Date Picker with fallback
// http://diveintohtml5.info/forms.html#type-date
var i = document.createElement("input");
i.setAttribute("type", "date");
if (i.type == "text") {
// No native date picker support :(
// Use jQuery UI to create one then dynamically replace that <input> element.
var jQueryUICSS = document.createElement('link');
jQueryUICSS.href = "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css";
jQueryUICSS.rel = "stylesheet";
document.getElementsByTagName('head')[0].appendChild(jQueryUICSS);
$.getScript("http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", function() {
$.datepicker.setDefaults(
$.extend($.datepicker.regional[''])
);
});
}
});
我想做的是使用 Paul Irish defined 的协议(protocol)相对方法确保 CSS 和 JS 都有本地后备。但根据 HTML5 Boilerplate 使用更新版本与此类似:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-ui.min.js"><\/script>')</script>
在最初的示例中,Javascript 正在创建一个 link
仅指向 jquery 网站的元素。我不太确定如何编写该协议(protocol)相关方法的第二行并使用 javascript 创建它。
类似地,getScript()
正在添加 jQuery UI js 文件。方法。如何添加此文件的本地版本仍允许 $.datepicker()
按预期加载?我不得不使用 getScript()
因为如果我不这样做,日期选择器会抛出一个控制台错误,指出它未定义。
如何将本地文件的后备方法包含到我已经编写的代码中?
最佳答案
您可以使用Promise pattern :
$.getScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js")
.then(null, function handleError() {
console.log("first try failed, loading local version");
return $.getScript("js/vendor/jquery-ui.min.js");
}).done(function() {
console.log("succeeded to load jQuery UI");
$.datepicker.setDefaults(
$.extend($.datepicker.regional[''])
);
}).fail(function(_, status, error) {
console.error("both attempts to load jQuery UI failed", status, error);
});
但是,似乎在某些 jQuery 版本中 $.getScript
function never fails on crossdomain scripts因此您可能需要为此使用超时。
关于javascript - 使用 native 输入类型的 jQuery UI 的协议(protocol)相对 URL 方法 ="date",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18882576/