Ajax Script Loading that Enforces Order of Execution

One awesome feature of jQuery is the ability to load external scripts on demand. The $.getScript method loads the script behind the scenes via ajax. In fact the function is simply an alias to call to jQuery’s $.ajax function. By default that alias does not look for a cached items. In my particular need I wanted to observe a cache and guarantee order of execution. I resorted to using the $.ajax function directly since it offers more options. I did not want a script to load before it’s dependency nor did I want to bog down my page by doing synchronous requests. In no time at all I built my own mechanism to handle script requests.

My code basically loads one script at a time and waits until it is completely loaded before iterating to the next file. Once they are all loaded it will call the loadComplete function which can take advantage of those scripts. This method will load scripts as memory and resources are available, then perform the final action when complete. The user could be presented a loading gif or progress bar in the meantime.

Below I am showing an example using CDN scripts: