<< Back

How to work with client-side includes

A common practice for websites with lots of pages is to store code that repeats multiple times in a separate file, and call upon it from each page, instead of hard-coding it each time by hand. Is it possible without a server-side programming language?

Well yes, somewhat.

In fact, Neocities users have been using little hacks to simulate server-side includes for a while. One of the most common ways to do that is with Javascript, and another is by using an <iframe> element. I'll show you how to do both.

Here is what you need to create an include effect with Javascript:

  1. First you need to make a separate file to store your included code in. The file must have a .js extension, and all the code inside the file must be wrapped in the document.write(); method, like so:

    Hint: in order to be able to write multiline strings with JS, you need to wrap them in a ` character. Usually it shares a button with your tilde key.
  2. Now that you have created your file, all you have to do to render it on your pages is to place a <script> tag where you want it to show, like this:

    And voila! You're all set.

And here is what you would do to make it work with <iframe>:

  1. Create an HTML file of the part you want to repeat on your pages, for example:

  2. Once done, on the page where you want to show your repeating code, add an <iframe> element with the path to your file, like so:

  3. By defaunt, an <iframe> will have some borders and a limited size, so make sure to spice it up with some CSS to make it look pretty.

And that's pretty much it!

Of course each method has it's own quirks, some of which are:

  1. An <iframe> requires additional CSS to look properly.
  2. Storing HTML in a JS script turns it into a string, instead of a DOM object, making working with it tricky.
  3. Both methods may negatively affect site performance, depending on the connection and file size.

Ultimately it is up to you to choose whichever method you like, for example I prefer the JS solution.

Anyway, I hope this was easy to understand. If something did not work, or you found some errors, do let me know! I'll be happy to help you or to fix any errors I made. Hope this article was of good use.