2014-01-07 53 views
1

我试图找出用户是否支持jQuery 2.x
这工作正常,但是当我尝试运行脚本时,它不起作用,因为jQuery没有完成加载...jQuery版本选择完成后运行

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(); 
}()); 
+1

你为什么用JavaScript这样做呢?使用条件注释来处理这个问题要容易得多,因为IE是唯一受影响的浏览器。 –

+0

好问题,哈哈,因为这个原因实际上,有老浏览器的人更新他们的浏览器... :-) –

回答

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; 
}()); 
+2

您可能想要在readystatechange处理程序之前删除内联'__run()'调用。 –

+0

是的,只是删除了__run()问题解决了。真棒家伙! –

+1

为什么使用onreadystatechange和onload?其实在你的代码中,你正在调用__run()3次,不是?! –

2

请与onreadystatechange

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

     __run(); 
    } 
}; 
+0

谢谢,但这不是解决方案,因为jQuery没有完成加载...... –

+0

@bvl ,更新了它 –