2015-10-14 38 views
1

不工作我有以下代码JS/jQuery的包括功能IE

function includeJSLib(lib, id, callback) { 
if (!document.getElementById(id)) { 
    var s = document.createElement('script'); 
    s.setAttribute('id', id); 
    s.setAttribute('async', 'false'); 
    s.setAttribute('type', 'text/javascript'); 
    s.src = lib; 
    document.getElementsByTagName('head')[0].appendChild(s); 
    s.onload = callback; 
} else { 
    callback(); 
} 
} 
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function(){ 
jQuery(document).ready(function($) { 
    if ($('body').hasClass('class')) { do something } 
}); 
}); 

它将加载jQuery的。在回调函数中有一些自定义代码。自定义代码在Firefox和Chrome中运行良好,但不在IE中运行。

Internet Explorer完全忽略了代码片段。在IE 10/11测试。

有没有人知道问题可能是什么?

感谢&问候, Noxx

附: IE调试器没有说什么,它只是跳过片段。我必须包括jQuery的这种方式(最好不要问:P)

+1

看看[这里](http://stackoverflow.com/questions/3248384/document-createelementscript-synchronous)问题。 –

+0

谢谢,但它不是有用的。加载过程和功能正在运行。只是在IE的情况下,它不工作。 – Noxx

+0

查看[this](http://stackoverflow.com/questions/16230886/trying-to-fire-onload-event-on-script-tag)的答案。 – shaunsantacruz

回答

1

对于IE浏览器,而不是onload使用onreadystatechange

function includeJSLib(lib, id, callback) { 
    if (!document.getElementById(id)) { 
    var s = document.createElement('script'); 
    s.setAttribute('id', id); 
    s.setAttribute('async', 'false'); 
    s.setAttribute('type', 'text/javascript'); 
    s.src = lib; 
    document.getElementsByTagName('head')[0].appendChild(s); 
    var loaded = false; 
    s.onload = s.onreadystatechange = function() { 
     var readyState = this.readyState || 'complete'; 
     if (!loaded && ('loaded' === readyState || 'complete' === readyState)) { 
     loaded = true; 
     // Handle memory leak in IE 
     s.onload = s.onreadystatechange = null; 
     s.parentNode.removeChild(s); 
     callback(); 
     } 
    }; 
    // s.onload = callback; 
    } else { 
    callback(); 
    } 
} 
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function() { 
    jQuery(document).ready(function($) { 
    if ($('body').hasClass('class')) { do something } 
    }); 
}); 
+0

就是这样,谢谢! – Noxx