How to Reduce, Reuse and Recycle Your Code

Amy
3 min readFeb 5, 2017

--

Have you ever had to change multiple html files because a link on your header or your footer has changed? Or maybe you no longer like the navigation hover color of #BADA55 and you find yourself having to go into every single file to change it to a more delicate color of LavenderBlush? There must be a way to change it once in one spot so you will have more time to play with fluffy the cat right? Well there is. There are several ways in fact but I’m going to mostly talk about a way that seems the most easy, straightforward and has decent browsers’ support. The magic happens with jQuery.

Here is a step by step example of how to reuse navigation bars in your html pages.

1. Save the code you wish to reuse into another html file.

In this example, I want to reuse code I have written for the navigation bars. I copy and pasted this code to a new file and saved it as reuseheader.html:

2. Add jQuery CDN to the head section of the html file you wish to reuse the code in.

3. Add jQuery script below the jQuery CDN in step 2 to load the reusable code html file.

The jQuery .load() method will be used to load the reusable html code file. To find more about the .load method, you can check out the documentation here: http://api.jquery.com/load/

$(‘#header’) specifies which html element to insert the reusable code into. In this case I have specified an html element with the ID of header.

$(function(){}); is short hand code for the $( document ).ready() function which will only run the code inside the function once the page Document Object Model (DOM) is ready for JavaScript code to execute. Since the JavaScript code is placed at the top and HTML gets loaded from top to bottom, this fixes the problem of running JavaScript code on html elements that haven’t been loaded.

4. Add <div> section, with ID that matches the ID in the jQuery code, into the html file in the section where you want the reusable code to appear.

In this case, I want the reusable code to appear between the <header> tags so I have given the <div> tag the ID of header.

And that’s it!

There are several other methods to achieve the same result, one of which is HTML5 Imports. You can read more about it here: http://blog.teamtreehouse.com/introduction-html-imports

The problem with this method is that it is not supported widely across browsers. A quick search in caniuse.com shows its limitations:

I’m sure in the future, HTML5 Imports will be the way to go but in the meantime, I’m going to stick to good old jQuery.

If you have any questions feel free to leave a comment!

--

--

Amy

Front-End Web Developer | Professional Engineer | Former Electrical Engineer | Globetrotter | Mommy of Milo🐶