使用Promise 动态加载
<button id="loadAndShowAlert">loadAndShowAlert</button>
<script>
document.getElementById('loadAndShowAlert').addEventListener('click', function () {
// 动态加载 SweetAlert2 库
loadScript('https://cdn.jsdelivr.net/npm/sweetalert2@11')
.then(() => {
// 库加载完成后调用 SweetAlert2 方法
Swal.fire({
title: '动态加载',
text: 'SweetAlert2 库已成功加载并显示弹窗',
icon: 'success',
confirmButtonText: '确定'
});
})
.catch((error) => {
console.error('Script load error:', error);
});
});
// 动态加载脚本的函数
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Script load error for ${src}`));
document.head.append(script);
});
}
</script>
Vue 使用案例
<script>
window.sunshine = {};
sunshine.vue_js_url = 'https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js';
sunshine.vue_callbacks = []
sunshine.loadVue = function (callback) {
sunshine.vue_callbacks.push(callback)
console.log('vue_callbacks', sunshine.vue_callbacks.length);
if (sunshine.vue_callbacks.length > 1) {
return;
}
var script = document.getElementById('sun-vue-js')
if (!script) {
script = document.createElement('script');
script.id = 'sun-vue-js';
script.src = sunshine.vue_js_url;
script.onload = () => {
while (sunshine.vue_callbacks.length) {
sunshine.vue_callbacks.shift()();
}
}
document.head.appendChild(script);
}
}
sunshine.ensureVueDependencies = function (callback) {
sunshine.loadVue(callback);
}
</script>
评论 (0)