Skip to content

Instantly share code, notes, and snippets.

@getify
Created August 26, 2011 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/1174213 to your computer and use it in GitHub Desktop.
Save getify/1174213 to your computer and use it in GitHub Desktop.
how to use LABjs to load nested resources serially, with callbacks
// look ma, I have no dependencies, no need for any wrappers!
alert("bar.js is loaded!");
// look ma, I have no dependencies, no need for any wrappers!
alert("baz.js is loaded!");
// i have a depedency, so i need to have a loader wrapping me
import_scripts(["baz.js"], function(){
alert("foo.js is loaded, including baz.js");
// put the payload for foo.js
});
<html>
<head>
<title>Look, serial loading with nested dependencies</title>
<script src="LAB.js"></script>
<script>
(function(){
var q = [], q_idx = 0;
function next_in_queue() {
if (q_idx < q.length) {
if (typeof q[q_idx] == "function") { // a callback found in the queue, so execute it
q[q_idx++]();
next_in_queue();
}
else {
$LAB.script(q[q_idx++]).wait(next_in_queue);
}
}
}
window.import_scripts = function(scripts,cb) {
var auto_start_queue = (q_idx >= q.length);
var splice_args = [].slice.call(scripts); // copy the passed in array of scripts
splice_args.unshift(q_idx,0); // put the first two arguments to `splice()` onto the front of the array
if (cb) splice_args.push(cb); // put the callback function, if any, on the end of the set of entries to push into the queue
[].splice.apply(q, splice_args); // send the arguments to `splice()`
if (auto_start_queue) next_in_queue();
};
})();
// list which scripts you want loaded into the page
import_scripts(["foo.js","bar.js"],function(){
alert("all my scripts are done loading now!");
});
</script>
</head>
<body>
<!-- ... -->
</body>
</head>
@bluej100
Copy link

Clever. This works well. The only downside is that it breaks LABjs's parallel downloads--bar.js won't start downloading until baz.js has been processed.

@bluej100
Copy link

I had to make a minor change to prevent a duplicate load when the last item in the queue contained an import_scripts. See my fork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment