1

There are no errors thrown in the code, so I can only assume either the events aren't getting triggered or they aren't getting added properly. Can anyone determine what the issue is here?

Code below. Fiddle here.

$('#fake-body').append('init<br />');
var scriptTag,
scriptsLoaded = 0,
scripts = ['//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js', '//codeorigin.jquery.com/ui/1.9.2/jquery-ui.min.js'],
scriptLoadedCallback = function(val) {
  scriptsLoaded++;
  $('#fake-body').append('callback called for '+val+' | scriptsloaded = '+scriptsloaded+' & length = '+scripts.length+'<br />');
  if(scriptsLoaded === scripts.length) {
    $('#fake-body').append('all loaded');
  }
};

$.each(scripts, function(index, value) {
  $('#fake-body').append('preparing '+value+'<br />');
  scriptTag = document.createElement('script');
  scriptTag.type = 'text/javascript';
  scriptTag.src = value;
  if(typeof scriptTag.addEventListener !== 'undefined') {
    $('#fake-body').append('add event for good browsers<br />');
    scriptTag.addEventListener('load', (function() {
      scriptLoadedCallback(value);
    }), false);
  } else {
    $('#fake-body').append('add event for the other one<br />');
    scriptTag.attachEvent('onreadystatechange', function() {
      if(scriptTag.readyState === 'loaded') {
        scriptLoadedCallback(value);
      }
    });
  }
  $('#fake-body').append('appending script<br />');
  $('#fake-body').append(scriptTag);
});

$('#fake-body').append('complete');

1 Answer 1

2

use plain Javascript to load javascript files rather than jquery(because jquery won't fire the load callback in your current code), so replace :

$('#fake-body').append(scriptTag);

with:

$('#fake-body')[0].appendChild(scriptTag);

or if you insist to use jquery, you have to respect the following statements order (or use getScript):

$body.append(scriptTag);
scriptTag.attachEvent
scriptTag.src = scriptUrl;

jsfiddle

you have another error by referencing scriptsloaded rather than scriptsLoaded in the callback.

Sign up to request clarification or add additional context in comments.

1 Comment

Can't believe I didn't see this!? But I guess this is what I get for writing code at 3am... :P Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.