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.
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.
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>:
Create an HTML file of the part you want to repeat on your pages, for example:
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:
- 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:
- An <iframe> requires additional CSS to look properly.
- Storing HTML in a JS script turns it into a string, instead of a DOM object, making working with it tricky.
- 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.