我一直在使用多种不同的方式来为我正在构建的网站包含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?这会产生一个很长的列表,对我而言似乎效率低下,因为许多页面不需要为这些文件定义链接。
答案 0 :(得分:2)
您可以将每个需要的css或JS的src添加到数组(PHP变量)。 然后在页面的末尾(在关闭正文之前),添加你的和标签。
<?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>
答案 1 :(得分:2)
我会做以下事情:
require
或include
插入标题,根据全局变量添加CSS文件include
或require
您的页脚文件,它根据全局变量插入所有JS文件(它是recommended以包含文件末尾的JS文件以防止页面加载延迟)答案 2 :(得分:0)
您可以为带有图像滚动条的页面使用不同的标题模板,并在该标题中包含图像滚动条css。
您可以在页面的任何位置添加Javascript文件,事实上有些人认为最好将它们包含在页面底部,因此它们会在HTML内容之后加载,因此不会延迟加载内容。但是我相信CSS文件必须始终包含在head标签中。
答案 3 :(得分:0)
头:
<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' ?>