I am always rewriting my headers and footers and for every edit i have to manually copy and paste all the code into the web pages. Obviously this is the wrong approach but im not sure of the right one. My current idea is to have a "header" and "footer" div and then with jquery's $(document).ready load the divs with code. Im afraid it will be slow though because it waits for the whole page to render before executing the header/footer code. What is a common way to handle this problem?
Commonly, there's some server-side templating technology in use, such as PHP, JSP or XSL. Creating reusable pieces of code which can be linked is fairly simple using one of these approaches.
For a pure HTML + JS approach, you could use an IFRAME to link to a standalone header and footer HTML file. That would allow you to keep all the header and footer information in one place, only needing to update it once.
Sounds like you need some server-side technology. Which one (of the many options) you choose is up to you and your hosting. Most likely, your hosting will support PHP and SSI (Server-side includes).
In the simplest setup, basically put the common code into individual files, let's say header.inc
and footer.inc
. It doesn't matter what the name or extension of these files are.
For PHP, your pages should now be *.php
instead of *.html
and you need to write this code:
<?php include('header.inc'); ?>
<p>
Here is your regular document.
</p>
<?php include('footer.inc'); ?>
For SSI, you don't have to change the names of your files, and your code would look like this:
<!--#include virtual="header.inc" -->
<p>
Here is your regular document.
</p>
<!--#include virtual="footer.inc" -->
You definitely don't want to do this with Javascript. First off, the header and footer won't load until the Javascript executes, but more important, anyone without Javascript enabled won't see them at all (and requiring Javascript to view a static page doesn't make sense).
There are two easy methods to do this:
1) Use a server-side language like php to include the footers:
<?php
include('header.html');
?>
The rest of the page goes here
<?php
include('footer.html');
?>
2) Use a build/deploy process that generates static pages. This would be similar to 1) but it would only be done once per build, rather than every time someone hits the page.