android phonegap
android phonegap

Reputation: 830

How to handle common code in multiple HTML's using javascript or jQuery

I have an application which has almost 30 html's and they share some common code to which i f i made any changes i need to change it on every page. Below is the piece of code which i am using on all pages.

<div>
  <ul>
    <li class="current"><a href=".html" ></a></li>
    <li><a href=".html"></a></li>
    <li><a href=".html"></a></li>
    <li><a href=".html"></a></li>
  </ul>
 </div>

Is there any solution to which i can keep it on a single file and reuse it where ever i want?

Upvotes: 14

Views: 12207

Answers (5)

elbrant
elbrant

Reputation: 791

Ancient post, but I think I might have a viable best-case solution:

  1. Create a JS file that contains your common data using an IIFE (Immediately Invoked Function Expression), such as: externalFile.js:

(function IIFE() { document.getElementById("sample").innerHTML = '<div><ul><li class="current"><a href=".html"></a></li><li><a href=".html"></a></li><li><a href=".html"></a></li><li><a href=".html></a></li></ul></div>'; })();

  1. Link the external file in your page head: <script src="external.js" defer></script>
  2. Add your div (or other tags) to your HTML: <div id="sample"></div>
  3. Add the <script> and <div> tags to each page.

This was/is the best solution I could think of to mimic Server Side Includes using only HTML, CSS, & JS. Why this way?

  • An IIFE will call itself, so you don't have to add any extra steps to it.
  • You can edit or adjust the content of the "externalFile.js" and have the change take place on all of your (related) pages.
  • Adding 'defer' to your JS link allows the content to be tucked into place as the page is loaded.
  • It's super flexible because you can add as many Element Selectors as you need for your site, all in the same JS file. So, your header, navigation, footer, side panel, etc., can all be laid out in one JS file.

Upvotes: 0

S R Samy
S R Samy

Reputation: 35

Old thread, but came across this requirement myself. My requirement was to do it in the client side with plain javascript. One off case, that is, only one html (appHeader.html) as common code.

In each of the required pages, defined a containing div with id="head-container" and in the body/window onload event, included

    await fetch("./appHeader.html")
    .then(response => response.text())
    .then((html) => {
        document.getElementById("head-container").insertAdjacentHTML("afterbegin", html);
    });

Upvotes: 0

Sunyatasattva
Sunyatasattva

Reputation: 5840

There are several ways you can achieve this inclusion to keep your code more maintainable.

PHP


Of course the first that comes to mind is if you want to use PHP is the usage of include() which includes and evaluates the code in your external file or script.

You can use it as such:

<?php include('path/to/file.html'); ?>

Note! Be careful: your container file must be a .php file in order for this directive to be evaluated from the server. You don't need to do anything but changing the file extension, for that to happen. And, of course, make sure that your server can parse PHP.

Also, beware of the difference with include_once(), which I would not recommend in this case.

SSI (Server side include)


If you don't want to use PHP, you can do that very simple and clean with a Server side include[Wikipedia]. An SSI looks like an HTML comment:

<!--#include virtual="your.html" -->

Note! You will have to make sure to have mod_include installed and enabled in your Apache server, and to add the following directive either in your httpd.conf or .htaccess file:

Options +Includes

Read the doc link above for more information.

Client-side includes


Your question actually specifies to do this in JS or jQuery. Not sure if it does because you were not aware of the server-side options, or if you really wanted a client-side one. In any case, there are also some client-side solutions.

Given the possibility, I would recommend the server-side solutions to your problem.

IFrame element


The <iframe> element includes content from an external file in a separate area in your page. You can use it like so:

<iframe src="your.html" width="x" height="y"><p>Fallback text</p></iframe>

Object element


The <object> element does a similar thing to the <iframe>, but while the latter is designed more as a means to sandbox an application, the former feels more integrated in your page. The usage is as follows:

<object type="text/html" data="your.html"></object>

Javascript insertion


Convert the code into a Javascript file and instruct the file to insert the content into the DOM. Here is an example

external.js

var element = '<div>
                   <ul>
                     <li class="current"><a href=".html" ></a></li>
                     <li><a href=".html"></a></li>
                     <li><a href=".html"></a></li>
                     <li><a href=".html"></a></li>
                   </ul>
               </div>';

container.html

<script type="text/javascript" src="external.js"></script>
<script>
     document.getElementById('#containing-element').innerHTML(element);
</script>

AJAX


jQuery can help you deal with some AJAX calls easily. You could use jQuery.get() or jQuery.load(). I would suggest you use the latter, as load() injects the loaded element directly into the DOM, and also as you can specify exactly which part to load, which is nifty especially if you would like to store all your includes in one external HTML file.

jQuery(document).ready(function ($){
    $('#containing-element').load('your.html');
});

Upvotes: 17

Johan
Johan

Reputation: 19072

If you use php you can have that code in one single file and use include 'filename.php';

http://php.net/manual/en/function.include.php

Upvotes: -1

Narek
Narek

Reputation: 3823

You already got answer for PHP, but if you don't want or can't use it you can save it in JS file: test.js

document.write('<div>\n\
  <ul>\n\
    <li class="current"><a href=".html" ></a></li>\n\
    <li><a href=".html"></a></li>\n\
    <li><a href=".html"></a></li>\n\
    <li><a href=".html"></a></li>\n\
  </ul>\n\
 </div>');

and include it:

<script type="text/javascript" src="test.js"></script>

But of course better with PHP.

Upvotes: -1

Related Questions