我正在尝试使用服务器端包含系统以模块化方式组织我的网站。我们的想法是每个模块都有自己的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刚刚加载,并确保它有一个很好的布局。
然而 - 我的解决方案遇到了一些问题:
这些包含可以与任何include,php,asp或jsp交换......这是使用apache SSI。
整个想法是否朝着错误的方向发展?我想这个用于开发设置,但是有一些加载页面的智能nodejs rhino脚本 - 找到加载的脚本和css,concats并缩小并添加为生产的单个包含。
答案 0 :(得分:0)
要解决包含js或css的问题,您应该将这些文件包含在您要包含的文件的顶部,而不是包含在该文件中。意味着你的product.css / js应该从中删除,并且应该放在index.html或标题.html中一次
包括相同的js可能会停止你的javascript,所以确保它们没有相互冲突
答案 1 :(得分:0)
使用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是一个不错的选择。总有一天我会写一篇博客,深入讨论这些内容。
minifying的聪明才智也存在于requirejs中。 requirejs optimizer