包括js库从头部内部开始,特定于一个页面

时间:2015-01-08 13:29:18

标签: php structure javascript html-head

我在我的项目中只在一个页面中使用谷歌图表js库,我有外部和全局页眉和页脚。 head标签位于head.php文件中,并且必需的js库包含在其中。我的网页剖析是这样的:

<?php
require('header.php');
?>

<div>my body elements of this page lie here </div>

<?php
require('footer.php');
?>

我可以在header.php中添加google图表库。它将被加载到每个页面中,但我只在一页中需要它。所以,我不想让加载进度变慢。只有在我加载此特定页面时,如何才能包含该库?可能吗?提前谢谢。

3 个答案:

答案 0 :(得分:3)

只需在包含标题之前添加变量,并在header.php

中检查该变量
<?php
//page that requires the js
$chartjs = true;
require('header.php');
?>

<div>my body elements of this page lie here </div>

<?php
require('footer.php');
?>

<?php
//header.php
if(isset($chartjs) && $chartjs){
    //inlcude js file here
}

答案 1 :(得分:0)

或者,您可以根据页面的上下文通过JavaScript有条件地加载它,我将在这里使用jQuery以便于使用Ajax方面,例如:

Page Body:

<div class="chart"></div>

的header.php

<script>
     var $charts = $('.chart');
     if ( $charts.length ) {
         $.getScript("charts.js", function(){
              $charts.plot(); //init.
         });
     }
</script>

但是这会延迟加载图表。另外,有关如何在没有jQuery库的情况下加载的参考,请参阅Load scripts after page has loaded?以获取有关页面后加载脚本的一些很好的参考。

参考$.getScript

答案 2 :(得分:0)

您有几种选择。一个是史蒂夫在答案中推荐的。

我想在图表页面中使用它:

require('header.php');
?>
<script type="text/javascript" src="chart.js"></script>

<div>my body elements of this page lie here </div>

<?php
require('footer.php');

另一种方法是检查$_SERVER["REQUEST_URI"],并仅包含在标题中,这是指定的页面。