Search code examples
performanceheaderlogichttprequestfooter

What is the most efficient way to write headers and footers, 'global' header/footer or 'local' ones?


I'm about to start coding a website, and because this is my first time writing a code for a webpage, there is something I've been wondering about.
Writing separate header.php and footer.php is probably the fastest and easiet way to do stuff.
The problem is, what if for some pages I'd like to use specific javascript files and codes and for some I would like to use others?
It would result in more HTTP request and will eventually impact the performance of the site.
I thought about using if statements in the header and just give every page exactly what it needs, and nothing more.

But which way is more efficient?:
Coding global header.php and footer.php files and separating the codes using if statements OR add the whole header+footer code to every single file (ie local header/footer)?

P.S global and local header/footer is something I just made up, didn't really know how to call it, lol.


Solution

  • The advantage of your "global" header and footer is that 1) they are consistent and changes are "global" and 2) they are included in the pages in server code. So there isn't a lot of HTTP traffic if you do the include on the server side.

    You can (and should) do page-specific includes on the server side if at all possible using logic that determines what to load at the time of the Request.

    There are other ways to accomplish this but with straight up PHP, what you are considering is the best way.

    If you are using a framework like Yii, you can do this sort of thing in layouts but with simple PHP, you are on the right track.

    Defining the header and footer in each page (local), causes you to repeat a lot of code and causes maintenance headaches going forward. You have a lot of pages to update for simple header/footer changes.