Author: Jon Davis <jon@jondavis.net>
The blog page that explains using.js is here: http://www.jondavis.net/blog/post/2008/04/Javascript-Introducing-Using-(js).aspx
This is a quick and dirty test of using.js. The using.js (4kb) script allows you specify a dependency script with its source URL for a particular feature so that it can be late-loaded, but it will not re-load the source twice. There is no dependency upon other script libraries like jQuery to get started with using.js.
The callback is truly synchronous (no wait) or else the asynchronous delay
after the referenced URL is fetched is set using
using.wait=[milliseconds];. You can reference
scripts on different domains by setting the global using.wait
property, or in using.reference() by passing true
and/or an optional milliseconds parameter before each URL, i.e.
using.register(true, 750, 'http://cachefile.net/scripts/jquery/1.2.3/jquery-1.2.3.js');.
The URL parameter in using.register()can take several URLs, not just one, as additional parameters to the using.register() function.
You do not need a callback function when calling using() if you just want to make sure the referenced script is loaded. using('jquery'); works fine as long as it has been pre-registered.
The big advantage of using.js is that you can manage one source script that does nothing but register a big list of script files by name, then in a larger web client app you can reference using.js and the registrations script and then have all you need for your app.
Test: Click on the buttons below more than once:
Test source code:
<html>
<head>
<script language="JavaScript" type="text/javascript" src="using.js"></script>
<script language="JavaScript" type="text/javascript">
using.register('hello',
'helloworld.js'
);
using.register('hello2',
'helloworld2.js'
);
using.register('moo',
true, 500, // async needed cause I'm gonna be fetching moo tools from another domain
'http://cachefile.net/scripts/mootools/1.11/mootools_full_1.11_packed.js'
);
using.register('multi',
'dep1.js',
'dep2.js'
);
</script>
</head>
<body>
<button onclick="using('hello', function() {alert(window.hello_isLoaded());}); ">helloworld.js</button>
<button onclick="using('hello2');">no callback</button>
<button onclick="document.body.style.cursor='wait';using('moo', function() {
document.body.style.cursor='default';
alert('moo! .. random: ' + $random(1,5));});">moo tools</button>
<button onclick="using('multi', function() {alert('dep1: ' + window.dep1 + ', dep2: '
+ window.dep2);});">multiple dependencies</button>
</body>
</html>
[helloworld.js]
window.hello_isLoaded = function(){
window.hello_isLoaded = function() {
return "I'm already loaded.";
}
return "Hello world! I'm loaded!!";
}
[helloworld2.js]
alert ("helloworld2.js loaded");
[dep1.js]
window.dep1 = 'loaded';
[dep2.js]
window.dep2 = 'loaded';