繁体   English   中英

包括html片段作为模块

[英]Including html fragments as modules

我正在尝试使用服务器端包含系统以模块化方式组织网站。 这个想法是,每个模块都将拥有自己的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次-我将同时包含20次css和js文件。 不好。
  2. 通常,我已经看到css包含在head标签中,而js包含在正文末尾。 在构建文档时让它们全部出现会引起任何问题吗?

这些include可以与任何include,php,asp或jsp交换...这是使用apache SSI。

整个想法是否朝错误的方向发展? 我可以想象这是用于开发设置的,但是有某种智能的nodejs rhino脚本可以加载页面-查找加载的脚本和css,concats并最小化并添加为单个包含以用于生产。

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

多次包含相同的js可能会使您的JavaScript停止运行,因此请确保它们不会相互冲突

使用javascript模块系统。 Javascript AMD模块requirejs可以无缝加载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加载完成后也需要进行样式设置。 在requirejs中使用!DomReader是一个不错的选择。 有一天,我将写一个博客,深入讨论这些问题。

最小化的智能性也存在于requirejs中。 requirejs优化器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM