一个js延迟加载的类库

一直希望做一个可以动态的装载js的小类库,可是一直太忙,不过今天居然发现已经有人做了一个。

http://www.jondavis.net/blog/post/2008/04/Javascript-Introducing-Using-(js).aspx

不过他的级别只是到了文件,而我觉得控制的粒度最好能到对象的级别,这样就不会扔一堆没用的东西在内存里了。

------------------------

Javascript: Introducing Using (.js)

by Jon 4/12/2008 3:37:00 PM

I'm releasing v1.0 of using.js which introduces a new way of declaring dependency scripts in Javscript.

http://www.jondavis.net/codeprojects/using.js/

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值