程序员人生 网站导航

Javascript插件类库组织与管理

栏目:jscript时间:2013-10-08 03:24:18
  网(LieHuo.Net)教程 在开发一个较大规模的网站,js插件类库应用的是相当多。那么自然在一个页面里就存在不少script和script相关的link标记,这样js组织与管理自然成了一大问题。

  先举个例子,比如jquery插件中的calendar在一个页面中就得有如下代码

以下为引用的内容:
<style type="text/css">
@import ""script/calendar/jquery.datepick.css";
</style>
<script type="text/javascript" src="script/jquery1.3.2.js"></script>
<script type="text/javascript" src=""script/calendar/jquery.datepick.js"></script>
<script type="text/javascript" src=""script/calendar/jquery.datepick-zh-CN.js"></script>

  看上面代码,calendar代码得运用四个相关的文件。其中jquery1.3.2.js是必须的,jquery.datepick-zh-CN.js依赖于jquery.datepick.js(日历插件),而jquery.datepick.css是插件的样式。

  运用以上代码得很小心的对待插件的依赖关系,主次关系不能换,移动文件路径还得改动文件src路径,以上script中下载js文件都是单线程下载,理想的是进行多线程下载(firebug看得出来),再者就是插件的缓存问题(插件更新了,客户端可能还保存着原来的文件)。

  看过不少网上关于这方面的解决方案,博客园中有SmartScript和javaeye中有JSI,它们貌似都存在一个boot.js文件。而我的解决方案就只需要一个script后面跟插件参数即可。

  以下是我对上述问题的一个解决方案:

以下为引用的内容:
<script type="text/javascript" src="script.do?plugins=calendar"></script>

  在一个页面中只需要js应用的插件只需要script.do后跟参数后插件名参数即可,其它的工作就是在整体写一个插件资源配置文件(写插件配置的人得弄清楚js相关资源,这个只需要配置一次),至于其它什么也不需要弄。

  插件资源配置文件

以下为引用的内容:
<?xml version="1.0" encoding="utf-8" ?>
<script path="script/plugins/" name="script/jquery1.3.2.js" lazy="script/plugins/lazy/jquery.lazy-1.3.1.js">
<!--自动完成-->
<plugin name="autocomplete" file="autocomplete/jquery.autocomplete.js">
<lazy file="autocomplete/jquery.autocomplete.css"></lazy>
</plugin>
<!--日历-->
<plugin name="calendar" file="calendar/jquery.datepick.pack.js">
<lazy file="calendar/jquery.datepick.css"></lazy>
<lazy file="calendar/jquery.datepick-zh-CN.js"></lazy>
</plugin>
<!--提示框-->
<plugin name="tip" file="tip/jquery.tip.js">
<lazy file="tip/bs.css"></lazy>
</plugin>
<!--拖动-->
<plugin name="draggable" file="jquery.draggable.js">
<lazy file="ui/ui.core.js"></lazy>
<lazy file="draggable/ui.draggable.css"></lazy>
</plugin>
<!--拖动放下-->
<plugin name="droppable" file="jquery.droppable.js">
<lazy file="ui/ui.core.js"></lazy>
<lazy file="droppable/ui.droppable.css"></lazy>
<lazy file="draggable/ui.draggable.js"></lazy>
<lazy file="draggable/ui.draggable.css"></lazy>
</plugin>
</script>


  html示例代码:


提示:可修改后代码再运行!

  相关代码下载

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐