narseoh
narseoh

Reputation: 55

Manage Header and Footer inclusion in php

lets assume that I want to organize my pages as following:

<?php include('header.inc.php'); ?>

my-page-content

<?php include('footer.inc.php'); ?>

in the header we have .css files and in the footer we have .js files.

how do I do if I want to load only the CSS and JS that the current page needs?

for example, on the article page I don't need to load the JS resources that manage maps and calendar.

Upvotes: 2

Views: 219

Answers (1)

Petr Fořt Fru-Fru
Petr Fořt Fru-Fru

Reputation: 1006

Personally, I think it is useless to insert other files into html that will never be used - for cache management purposes. The smaller the html cache space used, the more efficient and powerful the html page will be.

Consider the following example:

file: library.php

<?php
   function includeFiles(string $typeFile, array $source_arr, array $request_file): array
   {
     $tmp = [];
     $element = $typeFile === "css" ? "<link rel=\"stylesheet\" href=\"%s\">" : "<script src=\"%s\"><script>";
     foreach ($request_file as $file) {
       if (array_key_exists($file, $source_arr)) {
         array_push($tmp, [sprintf($element, "https://example.com" .$css[$file])]);
       }
     }
     return count($tmp) > 0 ? $tmp : false;
   }

  // Make a list of all .js and .css files using the php array:
  $css = [
    // List all the .css files you are using here
    "css1" => "/css/css1.css",
    "css2" => "/css/css2.css",
    "css3" => "/css/css3.css",
    "css4" => "/css/css4.css",
    "css5" => "/css/css5.css"
  ];


  $js = [
    // List all the .js files you are using here
    "js1" => "/js/js1.js",
    "js2" => "/js/js2.js",
    "js3" => "/js/js3.js",
    "js4" => "/js/js4.js"
  ];
?>

file: main_html.php

<?php   
  include "library.php";

  $css_files = ["css1", "css3", "css5"];
  $headers = implode(PHP_EOL, includeFiles("css", $css, $css_files));

  $js_files = ["js1", "js3", "js5"]; 
  $footer = implode(PHP_EOL, includeFiles("js", $js, $js_files));
  
?>
<!-- Here html -->
<!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
    
      <?php echo $headers; ?>

      <!-- and other your required head element parameters -->
    </head>
    <body> 
    
    <!-- includes .js files -->

    <?php echo $footer; ?>      

    </body>
  </html>
 

Upvotes: 1

Related Questions