包括html片段作为模块



我正试图使用服务器端包含系统以模块化的方式组织我的网站。这个想法是,每个模块将有它自己的css和自己的javascript,只会被加载一旦包含在页面上-所以任何页面没有模块不会加载模块的css/js。

我是这样做的:

header.html
-----------
<!-- header start -->
<link rel="stylesheet" href="css/header.css">
<header class="module-header">
    <div class="links">
       links...
    </div>
</header>
<script src="js/header.js"></script>
<!-- header end -->

footer.html
-----------
<!-- footer start -->
<link rel="stylesheet" href="css/footer.css">
<header class="module-footer">
    <div class="links">
       links...
    </div>
</header>
<script src="js/footer.js"></script>
<!-- footer end -->

,然后在index.html:

<!DOCTYPE html>
    <head>
        <title>Modular page</title>
    </head>
    <body>
        <!--#include virtual="html/header.html" -->
        <!--#include virtual="html/footer.html" -->
    </body>
</html>

这样可以很好地工作,并且由于脚本是在每个模块之后加载的,因此可以保证在运行脚本之前内容已经存在。Css是加载之前,并确保它将有一个漂亮的布局。

然而,我遇到了一些问题与我的解决方案:

  1. 如果我要包含一个模块几次,例如一个product.html,这将被重复说20次-我将有css和js文件也包括20次。不好。
  2. 一般来说,我看到css被包含在头部标签,js在正文的末尾。在文件编制过程中让他们都来,会引起什么问题吗?

这些包括可以与任何包括,php, asp或jsp交换…

整个想法是在错误的方向吗?我想这是为开发设置,但有某种智能nodejs犀牛脚本加载页面-找到加载的脚本和css, concats和最小化,并添加为生产的单个包含。

为了克服多次包含js或css的问题,你应该将这些文件包含在要包含的文件的顶部,而不是包含在该文件中。这意味着你的product。css/js应该从其中删除,应该放在你的index.html或header .html中一次

多次包含相同的js可能会导致javascript停止,所以请确保它们不会相互冲突

使用javascript模块系统。Javascript AMD模块要求加载Javascript增量是一个很好的选择。requirejs.org是一个很好的起点。

对于你的上下文使用

//inside header.html
require(['header.js'], function(){
   //call this require() multiple times it will load the javascript only once.
   //user header.js ... once this line is require() line is executed the
   //header.js will be loaded forever
});

页脚

//inside footer.html
require(['footer.js'], function(){
   //call this require() multiple times it will load the javascript only once.
   //user header.js ... once this line is require() line is executed the
   //header.js will be loaded forever
});

现在出现了以模块化方式加载CSS的问题。Requirejs CSS插件也可用。

现在,一旦你开始使用这种系统,脚本加载发生异步使用javascript。所以剧本在屏幕上出现得有点晚。甚至css也来得有点晚。因此,如果你正在编写全局事件处理程序,如window.onload= func(){},这些将会失败,因为你的大部分javascript还没有加载。如果你在动态加载的CSS上做样式,也需要在CSS加载完成后完成。在需求中使用DomReader是一个不错的选择。有一天我会写一篇博客来深入讨论这些问题。

最小化的聪明之处也存在于需求中。requirejs优化器