Ajaxian writes about using.js library created by Jon Davis. It allows for loading javascript files on demand, just before you need it. For more details on this please see Ajaxian and original post by Jon. I'll write about differences in his and ours approaches.
Jon requires you to first register script, mapping logacal name to physical address, and then you can load it by logical name where it's necessary. Code looks like this:
// potential scripts are pre-registered first
using.register("jquery", "/scripts/jquery-1.2.3.js");
// later, when actually needed
using("jquery"); // loads jQuery and de-registers jQuery from using
$("a").css("text-decoration", "none");
// or asynchronously
using("jquery", function() {
$("a").css("text-decoration", "none");
});
First of all it looks for me that synchronous "using" is bad idea because it blocks all page activities. If you have delays during script loading the page will "hung". Async is OK and I have similar vision about this. But I don't like using.register() here. Any script you may want to use later you must register in this manner. Let's say that we have several script components developed independently, but on the same set of base libraries. We want to build pages using some different combinations of these components — now we can't tell what combinations we'd use. How should we register script dependencies in this case? Perhaps, we could register used scrips right in the prologue of each script component. But in this case all components must agree on the same name for common script registering. I.e. in all of them "jquery" should point to the jQuery, or components will start to interfere with each other.
We have our own "using" library and you use it in the following manner:
SDF.Using(
"/lib/megalib.js",
"myscript.js",
function() {
...
}
);
Features:
- You don't have to register script URL with shorter name before using.
- You can specify as many scripts as you want.
- If you'd load script explicitly with <script> tag then library won't load this again.
- Library more or less understands relative paths so "/myscrips/myscrip.js" and "myscript.js" are the same, if your current dir is "/myscripts".
- It always works asynchronously.
We also didn't want to tinker with DOM by ourselves, so our library is based on jQuery. I belive it's better not to duplicate core functionality.
Additionally
There is the JSLoad library developed by instructables. IMHO, also is not very good for independent components.
Posted
Apr 16 2008, 03:12 AM
by
Andrew Mayorov