0

I'm trying to build an ajax script loader, but I'm running into the issue where I'm sending pieces of my combined file over twice (ie. jquery, bunched up with other scripts, is getting sent over twice because it's required by some (ajax) requested script sent over the wire.

My first thought was that I would just append md5 chunks onto the file name and if the requested script matches a piece of that, don't send - but this doesn't scale well for say.. 100 bundled scripts.

Anyone have any other suggestions?

Thanks!

Matt Mueller

Matt
  • 22,224
  • 25
  • 80
  • 116
  • I don't understand. Which script is supposed to detect which scripts are loaded? How would adding file names prevent new scripts from getting loaded through Ajax? – Pekka Nov 02 '10 at 21:28
  • It would probably be a script that comes down in the combined file that has a 'require' method to make further calls to the server to get back scripts IF they are not already present. – Matt Nov 02 '10 at 21:32

1 Answers1

1

I think it depends on the script types. Personally I'd define the libraries that are available and then just test to see if the object has been defined.

WAG example here, just off the top of my head (in my opinion this method could be pretty heinous to use on a regular basis but would be faster than individually identifying text.)

//javascript loader shell
var loader = function(){

    var loadLibrary = function(libraryName, fn){
        //your code to verify and download library or collection here 

        //callback function
        return fn();
    }

    return {
        exec: function(libraryName, fn){
           if(typeof(eval('window.'+libraryName)) != 'undefined'){
               return fn();
           } else {
               return loadLibrary(libraryName, fn);
           }
        }
    }   
}();

//example usage
loader.exec('util', function(){util.test();});
Jason Benson
  • 3,371
  • 1
  • 19
  • 21
  • 1
    ew apologies, first post on stackoverflow didn't realize I was adding an "answer" (Note to others: don't use this :D) – Jason Benson Nov 02 '10 at 21:38
  • No man, this is great - thanks for the response. "Answers" could also be interpreted as "A nudge in the right direction" :-D – Matt Nov 02 '10 at 22:00