Asynchronous Script Loading Callback

前端 未结 3 1209
醉话见心
醉话见心 2020-11-30 02:33

http://jsfiddle.net/JamesKyle/HQDu6/

I\'ve created a short function based on Mathias Bynens Optimization of the Google Analytics asynchr

相关标签:
3条回答
  • 2020-11-30 03:06

    The other answers works well, but aren't super readable or require Promises. Here is my two cents:

    function loadScript(src, callback) {
        var script = document.createElement('script');
        script.setAttribute('src', src);
        script.addEventListener('load', callback);
        document.head.appendChild(script);
    },
    
    0 讨论(0)
  • 2020-11-30 03:10

    A more recent snippet:

    async function loadAsync(src) {
        const script = document.createElement('script');
        script.src = src;
        return new Promise((resolve, reject) => {
            script.onreadystatechange = function () {
                if (script.readyState === 'loaded' || script.readyState === 'complete') {
                    script.onreadystatechange = null;
                    resolve(true);
                }
            };
            document.getElementsByTagName('head')[0].appendChild(script);
        });
    }
    

    utilisation

      loadAsync(`https://....js`).then(_ => {
        //  ... script loaded here
      })
    

    James Kyle's answer doesn't take IE9 into account. Here is a modified version of the code I found in the link proposed in the comments. Modify the var baseUrl so it can find the script accordingly.

    //for requiring a script loaded asynchronously.
    function loadAsync(src, callback, relative){
        var baseUrl = "/resources/script/";
        var script = document.createElement('script');
        if(relative === true){
            script.src = baseUrl + src;  
        }else{
            script.src = src; 
        }
    
        if(callback !== null){
            if (script.readyState) { // IE, incl. IE9
                script.onreadystatechange = function() {
                    if (script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        callback();
                    }
                };
            } else {
                script.onload = function() { // Other browsers
                    callback();
                };
            }
        }
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    

    utilisation:

    loadAsync('https://www.gstatic.com/charts/loader.js' , function(){
        chart.loadCharts();
        });
    // OR relative path
    loadAsync('fastclick.js', null, true);
    
    0 讨论(0)
  • 2020-11-30 03:14

    Thanks RASG for https://stackoverflow.com/a/3211647/982924

    Async function with callback:

    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = '//' + u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
    

    Usage:

    async('snapabug.appspot.com/snapabug.js', function() {
        SnapABug.init('XXXXX-XXXXX-XXXXX-XXXXX-XXXXX');
    });
    

    jsFiddle

    0 讨论(0)
提交回复
热议问题