标签搜索

javascript 动态加载脚本

sunshine
2024-07-09 / 0 评论 / 47 阅读
温馨提示:
本文最后更新于2024年07月15日,已超过129天没有更新,若内容或图片失效,请留言反馈。

使用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>
感觉很棒,欢迎点赞 OR 打赏~
1
分享到:

评论 (0)

取消