Noxx
Noxx

Reputation: 21

Js/jQuery include function not working in IE

i have following Code

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 }
});
});

it will load jQuery. In the callback function there is some custom code. the custom code works fine in Firefox and Chrome but not in IE.

The internet Explorer totally ignores the code snippets. Tested in IE 10/11.

Does anybody have a idea what the problem could be?

Thanks & Regards, Noxx

p.s. The IE Debugger says nothing, it just jumps over the snippets. And i have to include jQuery this way (better dont ask :P)

Upvotes: 2

Views: 594

Answers (1)

Valentin Podkamennyi
Valentin Podkamennyi

Reputation: 7359

For IE instead of onload use 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 }
  });
});

Upvotes: 3

Related Questions