Tuesday, June 30th, 2009
Kyle told us:
What I wanted was a pattern where I could load scripts in parallel, just like with script tags, but also block and wait if there was an explicit ordering dependency that required it.
What most loaders fail to do well is let you define “dependencies” simply based on loading order. With regular script tags, the browser blocks for you, so you can make sure for instance that jquery.js loads before jqueryui.js. But imagine you’ve got 3 scripts that can download in parallel (not dependent on each other), and then two more that need to wait for those 3 to load. You can’t do that with script tags, and you also can’t do that very easily with a lot of the script loaders/frameworks that I’ve found.
Most of them rely on intrusive concepts to do “dependency” management. For instance, each child script has to “signal” (callback) that it’s done loading, to the parent page. Or the parent script and child scripts have to explicitly declare dependencies using some framework or conventions. Also, some other loader libraries rely on attaching a single load callback handler for EACH script. This makes it awkward or difficult to wait for several to load at a time, before proceeding, since you as the author have to keep track of what has loaded yourself.
jsLAB lets you load pretty much any script file, whether you control it or not, with no intrusion or convention for dependencies, other than the order and blocking that you define. It keeps track of what you’ve asked for and what has downloaded, only loads a unique script filename once, and lets you only define your handler once for a set of scripts that will load together in parallel. The API style (with chaining) makes is very easy to convert a set of script tags in your page into code to load them, without having to worry that race conditions will cause issues for scripts loading in the wrong order if there are implicit dependencies involved.
- <script src="jquery.js"></script>
- <script src="jquery.ui.js"></script>
- <script src="myplugin.jquery.js"></script>
- <script src="initpage.js"></script>
In the above example, “jquery.ui.js” and “myplugin.jquery.js” can load in parallel because there’s no dependencies, but they will wait for “jquery.js” to load first, since they depend on it, and then “initpage.js” will wait for all of them to load before it runs, to it makes sure all code it will call is in place, similar to a $document.ready(…) concept.
Posted by Dion Almaer at 6:16 am