Home > Software design >  A self contained Javascript/Html module - Is this possible?
A self contained Javascript/Html module - Is this possible?

Time:10-17

I have a div with associated javascript code. I would like to have the html for just this div and the associated javascript code all in one file, a kind of self contained 'module', eg

mydiv.html

<html>
<div id="Wibble" style="display: none;">
    ... loads of structure for just this div
</div>
<script type="text/javascript">
    ... loads of js functions just associated with this div
</script>
</html>

Then in my main page index.html I would like to include this 'module' in some way.

The only thing I have found is a Server Side Include:

index.html

<!DOCTYPE html>
<html>
<head>
    ... loads of stuff
</head>
<body>
   ... loads of other html structure

   <!--#include FILE="mydiv.html" -->

   ... loads of other html structure and script tags
</body>
</html>

Question 1: Is there a better way of doing this?

Question 2: Should I have the html tag in mydiv.html as that will obviously put an html tag in index.html which is out of place?

Question 3: If that html tag in Q2 should not be there, how do I write the mydiv.html file so it has all the formatting and nice coloured structure in Visual Studio Code?

CodePudding user response:

You can try importing from template elements. Here is a simplified templating example that may be useful.

If you need to import from an external file, check this example I cooked up for you.

document.querySelectorAll(`[data-import]`).forEach( el => {
  if (!el.dataset.imported) {
    el.appendChild(document.querySelector(`#${el.dataset.import}`)
      .content.cloneNode(true));
    el.dataset.imported = `ok`;
  }
});
<template id="someForm">
    <script>
      document.addEventListener(`click`, handle);
      function handle(evt) {
        if (evt.target.nodeName === `BUTTON`) {
          alert(`Yes. I am handled`);
        }
      }
    </script>
    <button id="sub">Handle me!</button>
</template>

<template id="somethingElse">
    <style type="text/css">
      .red {color: red;}
    </style>
    <p class="red">I am appended too</p>
</template>

<div data-import="someForm"></div>
<div data-import="somethingElse"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use an Iframe

<iframe id="inlineFrameExample"
    width="300"
    height="200"
    src="mydiv.html">

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

  • Related