I'm releasing v1.0 of using.js which introduces a new way of declaring dependency scripts in Javscript.
The way it works is simple. Add a <script src="using.js"> reference to the <head> tag:
<html>
<head>
<script type="text/javascript" language="javascript" src="using.js"></script>
<script type="text/javascript" language="javascript">
// your script here
</script>
</head>
<body> .. </body>
</html>
Then in your script, register your potential dependencies. (These will not get loaded until they get used!)
using.register("jquery", "/scripts/jquery-1.2.3.js");
Finally, when you need to begin invoking some functionality that requires your dependency invoke using():
using("jquery"); // loads jQuery and de-registers jQuery from using
$("a").css("text-decoration", "none");using("jquery"); // redundant calls to using() won't repeat fetch of jQuery because jquery was de-registered from using
$("a").css("color", "green");
Note that this is only synchronous if the global value of using.wait is 0 (the default). You can reference scripts on external domains if you precede the URL in the using.register() statement with true and/or with an integer milliseconds value, or if you set the global using.wait to something like 500 or 1000, but then you must write your dependency usage scripts with a callback. (UPDATE: v1.0.1: Simply providing a callback will also make the load asynchronous.) No problem, here's how it's done:
using.register("jquery", true, "http://cachefile.net/scripts/jquery-1.2.3.js");
using("jquery", function() {
$("a").css("text-decoration", "none"); //async callback
});
Oh, and by the way, using.register() supports multiple dependency script URLs.
using.register('multi', // 'multi' is the name
'/scripts/dep1.js', // dep1.js is the first dependency
'/scripts/dep2.js' // dep2.js is the secon dependency
);
The goals of using.js are to:
-
Seperate script dependencies from HTML markup (let the script framework figure out the dependencies it needs, not the designer).
-
Make script referencing as simple and easy as possible (no need to manage the HTML files)
-
Lazy load the scripts and not load them until and unless they are actually needed at runtime
If you have bug reports or suggestions, please post comments here or e-mail me at jon@jondavis.net.