Hi, > I was wondering if jQuery can be used to load javascript dynamically, > on an as-needed basis. Here is the problem I have: > > I want to load a page with as little javascript as possible.
jspax.org You don't even need to have jQuery loaded before. I do user jQuery as a jsPax Package. In the last fiew months I have recieved two reports that peolpe had problems with jsPax and IE. I do trust both of them because they definatelly are no idiots, but I have not been able to reproduce that problem up to now. > When > someone clicks on an item that requires some javascript functionality, > I want it to load a javascript function from an external file and then > execute it. Yes, with jsPax: $using('jQuery',function() { $(function() { $('.clickableElements').bind(click,function() { var self = this; $using('my.wonderful.package', function() { my.wonderful.package.handleClickOn(self); }); }); }); }); What a cascade of functions :-) > While there is some simple javascript I've found that can do this kind > of thing by appending the script to the DOM, it can't do things in > order. Those scripts do not work in some safari versions. If you whant your script to work there as well, you need to load it via XMLHttpRequest and execue it with exec(). Also adding a script tag loads the script assynchonously and does not give you information on when it has finished. jsPax uses XMLHttpRequest whenever it is available and calls your callback on success. Otherwies it adds two script tags. One with the script set as src and the second one with a script text inside that calls a special callback function. This callback function indirectly is a call your callback that you have given to the $using() function - just changing the context. The browser can not execute the second script before it has executed the first one. > I don't like the idea of doing a time-out loop, so I was > wondering if jQuery has something built in for this kind of thing. if you do have jQuery loaded, then it is fairly easy to mimic the behaviour of jsPax: $(function() { var clickScriptAvilable = false; $('.clickableElements').bind(click,function() { var self = this; if( clickScriptAvilable ) my.wonderful.package.handleClickOn(self); else $.getScript('my.my/wonderful/package.js', funciton() { clickScriptAvilable = true; my.wonderful.package.handleClickOn(self); }); }); }); IIRC getScript() always uses XMLHttpRequest without a fallback to inserting script tags. That is usually OK, because you usually don't take browsers into account that don't even have a XMLHttpRequest when you use jQuery. Actually in my daily work I don't take these into account as well, but I whanted jsPax to be able to even handle those. Christof