Bookmarklet wait until Javascript is loaded

前端 未结 4 1764
一个人的身影
一个人的身影 2020-12-04 16:58

I\'ve got a bookmarklet which loads jQuery and some other js libraries.

How do I:

  • Wait until the javascript library I\'m using is available/loaded. If
4条回答
  •  Happy的楠姐
    2020-12-04 17:49

    I've paid an attention that in Chrome the order of scripts that are loaded is undetermined, when using @Vincent Robert's technique. In this case a little modification helps:

    
    (function() {
        var callback = function() {
            // Do you work
        };
            // check for our library existence
        if (typeof (MyLib) == 'undefined') {
            var sources = [
                    'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
                'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
                'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
                'http://myhost.com/javascripts/mylib.min.js'];
    
            var loadNextScript = function() {
                if (sources.length > 0) {
                    var script = document.createElement('script');
                    script.src = sources.shift();
                    document.body.appendChild(script);
    
                    var done = false;
                    script.onload = script.onreadystatechange = function() {
                        if (!done
                                && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                            done = true;
    
                            // Handle memory leak in IE
                            script.onload = script.onreadystatechange = null;
    
                            loadNextScript();
                        }
                    }
                } else {
                    callback();
                }
            }
            loadNextScript();
    
        } else {
            callback();
        }
    })();
    

提交回复
热议问题