仅在必要时包含CSS/JS


Include CSS/JS only when necessary

我的菜单系统都来自索引文件。一个简化的例子:

#index.php
...
<div id="container">
include($inc_file) //index.php?site=news will show news.php
</div>
...

我的问题是:如何在需要的时候只包含一些js文件和css文件。例如,我有一个带有滑块的文件。我只想在访问该页面时包括与滑块相关的js/css文件。

我知道我可以写if/else条款,但我觉得有点无效。是否可以放置一个包含数组的会话,其中包含应该包含在首页上的所有文件?

以下是我要使用的:

<?php
$path_parts = pathinfo(__FILE__);
$filename = $path_parts['filename'];
if ($filename === "somepage") {
?>
<script src=""></script>
<link ...>
<?php } ?>

我只需要为每个页面预先设置一个数组,其中包含一个需要包含的css/js文件数组
例如
settings.php

<?php
$pages = array();
$pages['index'] = array(
    "css" => array("main.css","index.css"),
    "js"  => array("jquery.min.js","someotherjs.js")
);
$pages["about"] = array(
  ...
);

index.php

<?php
include('settings.php');

?>
...
<head>
    <?php
        foreach($pages['index']['css'] as $css)
            echo "<link rel='stylesheet' type='text/css' href='$css'>";
    ?>
    ...
    <?php
        foreach($pages['index']['js'] as $js)
            echo "<script src='$js'></script>";
    </body>
</head>

这可能不是您所期望的答案,但您知道浏览器不会下载自上次下载以来没有更改的cssjs文件吗。它们缓存在客户端PC上,只有在服务器上的副本发生更改时才会刷新。

因此,你可能不需要对每个页面上加载的内容如此挑剔,因为这可能不会导致css或js文件的新下载。

准备一个对象,您可以根据需要添加样式或js文件,这里有一个小例子。

class head {
    private styles = array();
    private scripts = array();
    public function __construct() {}
    // add script in page
    public function add_script(filepath){
       array_push($this->scripts, filepath);
    }
    // add style in page
    public function add_style(filepath){
       array_push($this->styles, filepath);
    }
    // get html <link> for styles
    public function get_styles(){
       $html = '';
       $len = count($this->styles);
       for($i=0; $i < $len; $i++){
           $html .='<link rel="stylesheet" type="text/css" href="'.$this->styles[$i].'">'; 
       }
       return $html;
    }
    // get html <script> for scripts
    public function get_scripts(){
       $html = '';
       $len = count($this->scripts);
       for($i=0; $i < $len; $i++){
           $html .='<script type="text/javascript" src="'.$this->scripts[$i].'"></script>'; 
       }
       return $html;
    }
 }
 // destruct ...

在您的控制器中:

require('/class/head.php');
$head = new head();
$head->add_style('/css/myStyle.css');
$head->add_script('/js/myScript.js');

头内

<?php echo $head->get_styles(); ?>
<?php echo $head->get_scripts(); ?>