How do I structure my HTML for good code reuse and maintenance?

MrKatSwordfish picture MrKatSwordfish · Jan 21, 2014 · Viewed 20.8k times · Source

I have a limited background in coding native apps using languages like C++, C, and Java, but now I'm trying to get into web development. While most of it is pretty simple and clean, I'm having a few problems understanding how I can create websites and webapps that do a good job reusing existing code where applicable. As I understand it, when using things like JavaScript, CSS, and PHP, you can simply import scripts from other files for use in any html file, which is very useful. But I'm having a hard time figuring out how this can be done with HTML, is it possible?

For example, say I have a single-page website with a 'header bar' and a bunch of unique content below (for example, the stackoverflow logo, the buttons, and the menus at the top of this page). But now, I want to expand my website and add 3 new pages that share a similar layout and have the exact same 'header bar' at the top. One way to achieve this might be to simply copy the that contains that part of the code and paste it into page2.html, page3.html, and page4.html; the unique code for each page would be separate, and it would work fine. The problem I have with this approach is that it makes it a really pain to alter the content of the 'header bar' without going through multiple pages of HTML, and the odds of creating weird inconsistencies in design/content becomes high. I'm guessing that "stackoverflow.com/questions/ask" and "stackoverflow.com/tags" don't contain duplicate, copy-and-pastes code for the elements at the top of the page, but I'm not sure how to achieve this due to my limited HTML experience..

So, is there some way of "including" or "importing" HTML code for the sake of clean code reuse across multiple pages? Is this functionality built into HTML or do I need to look deeper into things like JavaScript and PHP to create well-structured websites? I've searched for the answer to this, and a few people have suggested iframes, but then almost immediately suggested against their use in modern web design.. What might be a good approach?

Answer

skip405 picture skip405 · Jan 21, 2014

The possibility to include pieces of code is available now, but it lacks a proper browser support. It is called html-templates. In future this will allow you to create you own html-templates to avoid duplication of code. But for now.. not native HTML, only other technologies (PHP-based, Javascript-based, Ruby-based and what-not-based).