论坛首页 Web前端技术论坛

一个js延迟加载的类库

浏览 3410 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-14  

一直希望做一个可以动态的装载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.

   发表时间:2008-04-14  
不错,比JSI小
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics