完成jQuery版本选择后运行

时间:2014-01-07 15:44:18

标签: javascript jquery

我试图找出用户是否支持jQuery 2.x
这很好用,但是当我尝试运行脚本时它不起作用,因为jQuery没有加载... < / p>

如何在加载jQuery之后触发__run()

初始化脚本:

function __run(){
    //
    // function runs the jQuery website
    //  
    $("body").append( "<p>Test</p>" );
}

(function () {
    var s, s0, js;
    if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
        js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
    } else {
        js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
        alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
    }
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = js;
    s0 = document.getElementsByTagName('script')[0];
    s0.parentNode.insertBefore(s, s0);
    __run();
}());

2 个答案:

答案 0 :(得分:2)

选中onreadystatechange

s.onload = s.onreadystatechange = function(){
    if ( !done && (!this.readyState ||
    this.readyState == "loaded" || this.readyState == "complete") ) {

         __run();
    }
};

答案 1 :(得分:2)

试试这个

(function () {
    var s, s0, js;
    if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
        js = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
    } else {
        js = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
        alert('Woow, that\'s one old browser, maybe you should upgrade. We don\'t support this version, you can try to use the website though');
    }
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = js;
    s0 = document.getElementsByTagName('script')[0];
    s0.parentNode.insertBefore(s, s0);

    s.onreadystatechange= function () {
      if (this.readyState == 'complete') __run();
    }
    s.onload= __run;
}());