加载带有承诺的脚本,jQuery没有加载



我做错了什么?

文件被加载了,但我得到了一个"TypeError:$(…(.datepicker不是函数">

这是我第一次尝试承诺。

也许有更好的方法来实现

if (datePicker.type === "text") {
jqui = true;
function loadScript(url ,ext) {
return new Promise(function(resolve , reject) {

if(ext == 'js'){
let script = document.createElement("script");
script.type = 'text/javascript'
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.getElementsByTagName("head")[0].appendChild(script);
}else if(ext =='css'){
let script = document.createElement("link");
script.href = url
script.onload = resolve;
script.onerror = reject;
script.rel = 'stylesheet';
document.getElementsByTagName("head")[0].appendChild(script);
}
});
}
loadScript("https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js",'js').then(
loadScript("https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js",'js').then(
loadScript("https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/themes/ui-lightness/jquery-ui.css",'css').then(function() {
if(window.jQuery) {
$(".datepicker-btn").datepicker({
altField: ".converteddate",
altFormat: "dd-mm-yy",
});
$(".datepicker-btn").on("change", setDeliverSlots);
}else{
console.log('jquery error');
}
}, function() {
}), function() {
}), function() {   
});
}

所以我无法使用promise,所以我用不同的方式解决


const jq = document.createElement('script')
jq.src = 'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js';
const jui = document.createElement('script')
jui.src = 'https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js';
const css = document.createElement('link')
css.href = 'https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/themes/ui-lightness/jquery-ui.css';
css.type = 'text/css';
css.rel = "stylesheet";
const head = document.head || document.getElementsByTagName('head')[0];

head.appendChild(jq);
jq.addEventListener('load',function(){
console.log('jq laoded');
head.appendChild(jui);
jui.addEventListener('load',function(){
console.log('jui loaded');
head.appendChild(css)
css.addEventListener('load',function(){
console.log('css loaded');
if(window.jQuery){
$(".datepicker-btn").datepicker({altField: ".converteddate",altFormat: "dd-mm-yy"});
$(".datepicker-btn").on("change", setDeliverSlots);
console.log('loaded');
}else{
console.log('jq error');
}
})
})
})
}

最新更新