Hi,

> I'm afraid that I simply don't take Safari users into account. Hardly a
> great thing, but I focus on three browsers: Firefox and IE7, and then IE6.
> In that order. The work I do is targetted at corporate users who run
> Windows 2000 and Firefox, and all the JS work I do is for those users.

Then your solution is almost OK for you. Here is a usable version ;-)

(function() {
  var addScriptCounter = 0;

  function addScript( url, callback ) {
    var script = document.createElement( 'script' );
    script.myLoadHandler = callback;
    script.id = 'dynamicallyLoadedScript_'+addScriptCounter;
    script.type = 'text/javascript';
    script.charset = 'utf-8';
    script.src = url;

    var script2 = document.createElement( 'script' );
    script2.type = 'text/javascript';
    script2.charset = 'utf-8';
    script2.appendChild(
      document.createTextNode(
        '(function(){'+
          'document.getElementById(\'dynamicallyLoadedScript_'+
            addScriptCounter+'\').myLoadHandler();})()';
      ));

    var head = document.getElementsByTagName('head')[0];
    head.appendChild( script );
    head.appendChild( script2 );

    addScriptCounter++;
  }
})()

Usage:

addScript('jquery.js', function() {
        alert('horay, jQuery is available');
});
alert('jQuery is not necessarily available here');

The second script tag will be evaluated after the first one has been loaded 
and evaluated. At least that works for all browsers I have tested with, 
except those Safari versions and very old browsers without a usable DOM 
implementation. 

If jQuery cannot be loaded successfully (wrong url e.g.), your callback will 
still be called, and will fail as soon as it tries to access jQuery.

If you use a XMLHttpRequest, you can distinguish the case when loading was not 
successfull from successfull loading before you really call the callback. By 
the way you also get it working for Safari, but keep out those browsers 
without a XMLHttpRequest implementation. For them jsPax falls back to adding 
script tags via DOM.

That does not work only for the very old browsers without a usable DOM 
implementation. There is also a fallback for them in jsPax, but I have not 
really tested it, because I don't have such a browser at hand - theoretically 
it should work.

Christof

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to