2

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)

Noxx
  • 21
  • 2
  • 1
    Take a look at [this](http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously) question. – Anderson Pimentel Oct 14 '15 at 15:27
  • Thanks, but it isn't helpfull. The loading process and the functions are working. Just in case of IE it isnt working. – Noxx Oct 14 '15 at 15:34
  • Check out [this](http://stackoverflow.com/questions/16230886/trying-to-fire-onload-event-on-script-tag) answer as well. – shaunsantacruz Oct 14 '15 at 15:56

1 Answers1

3

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 }
  });
});
Valentin Podkamennyi
  • 7,161
  • 4
  • 29
  • 44