Waiting for dynamically loaded script

前端 未结 6 1745
忘了有多久
忘了有多久 2020-11-30 08:28

In my page body, I need to insert this code as the result of an AJAX call:

    

Loading jQuery

6条回答
  •  北海茫月
    2020-11-30 08:51

    Wait for multiple scripts to load

    The following helper loads multiple scripts only once and returns a promise:

    async function cirosantilli_load_scripts(script_urls) {
        function load(script_url) {
            return new Promise(function(resolve, reject) {
                if (cirosantilli_load_scripts.loaded.has(script_url)) {
                    resolve();
                } else {
                    var script = document.createElement('script');
                    script.onload = resolve;
                    script.src = script_url
                    document.head.appendChild(script);
                }
            });
        }
        var promises = [];
        for (const script_url of script_urls) {
            promises.push(load(script_url));
        }
        await Promise.all(promises);
        for (const script_url of script_urls) {
            cirosantilli_load_scripts.loaded.add(script_url);
        }
    }
    load_scripts.loaded = new Set();
    
    (async () => {
        await cirosantilli_load_scripts([
            'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js',
            'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js',
        ]);
    
        // Now do stuff with those scripts.
    
    })();
    

    GitHub upstream: definition and usage.

    Tested in Chromium 75.

提交回复
热议问题