我一直在尝试许多不同的方法来为我正在构建的网站包含header.php和footer.php文件。
我不确定的是引用网站上不同页面所需的几个。css和。js文件的最有效的地方。我已经按照如下方式设置了包含的页面(这些页面被简化到最小,以说明结构的重点):
header。php:
<html>
<head>
<title>Example Page 1</title>
<link rel="stylesheet" type="text/css" href="menu_styles.css"/>
<script type="text/javascript" src="main_menu.js"></script>
</head>
<body>
<!------MENU CODE HERE------>
后面跟着。php:
<?php
include 'header.php'
?>
<div>Page Content 1</div>
<div>Page Content 2</div>
<?php include 'footer.php' ?>
其中footer.php的最简单形式如下:
</body>
</html>
我可以看到在标题中引用menu_styles.css和main_menu.js的逻辑,因为这是菜单代码将始终写入的地方。然而,如果我有一个单独的页面,例如,一个图像滚动与自己所需的js/css文件,在哪里是最有效的方式来定义这些?我能在主页本身做还是我必须在header。php中定义每一个。css和。js ?这将产生一个很长的列表,对我来说似乎效率低下,因为许多页面不需要定义到这些文件的链接。
我会这样做:
- 创建一个包含所有CSS文件的全局变量,另一个包含所有Javascript文件的全局变量
- 在你的"whatever php文件"中,首先改变全局变量以包含正确的CSS文件和JS文件。
- 调用
require
或include
来插入头文件,这将根据全局变量 添加CSS文件。 - 在你的"whatever php"文件中做任何你需要的东西
-
include
或require
您的页脚文件,它插入基于全局变量的所有JS文件(建议在文档末尾包含JS文件以防止页面加载延迟)
您可以将每个需要的css或JS的src添加到数组(PHP变量)中。然后在页面末尾(在结束正文之前)添加and标签。
<?php
include 'header.php';
$css = array();
$js = array();
?>
<div>Page Content 1</div>
<div>Page Content 2</div>
// content and content imports may add sources to css and js arrays
// where footer.php prints <script> and <link> tags, importing needed css and js
<?php include 'footer.php' ?>
</body>
</html>
您可以为带有图像滚动条的页面使用不同的页眉模板,并且只需在该页眉中包含图像滚动条css。
你可以在页面的任何地方包含Javascript文件,事实上,一些人认为在页面的底部包含它们是更好的做法,这样它们就会在HTML内容之后加载,因此不会延迟内容的加载。但是,我认为CSS文件必须始终包含在header标签中。
header:
<html>
<head>
<title>Example Page 1</title>
<?php
if ($css_inc != NULL) {
foreach ($css_inc as $value) {
echo '<link type="text/css" href="' . $value . '"></link>';
}
}
if ($js_inc != NULL) {
foreach ($js_inc as $value) {
echo '<script type="text/javascript" src="' . $value . '"></script>';
}
}
?>
</head>
<body>
<!------MENU CODE HERE------>
page.php
<?php
$css_inc = array('style.css', ''public'css'gallery.css');
$js_inc = array('public.js', ''public'js'jquery.js', ''public'js'jqueryui.js');
include 'header.php'
?>
<div>Page Content 1</div>
<div>Page Content 2</div>
<?php include 'footer.php' ?>