Search code examples
javascriptmoduleinclude

A self contained Javascript/Html module - Is this possible?


[EDIT: I have possibly found another solution. Kooilnc's solution looks good. Is the solution at the bottom of this question better or worse than Kooilnc's?]

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?


Edit:

Kooilnc's solution (below in the answers) looks good. Here is another solution I have found. It is working in my development environment Visual Studio Code. I need the javascript in my included html file in body's onload. Does anyone know if this solution will work on a server with my body onload requirement? Is it better or worse than Kooilnc's solution?

Jquery must be included with the normal <script> tag prior to this.

I insert this code within index.html

<!DOCTYPE html>
<html>
<head>
    ... loads of stuff
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">  
</head>
<body>
   ... loads of other html structure

   <div id="include_mydiv"></div>
   <script>
       $(function(){
           $("#include_mydiv").load("mydiv.html");
       });
   </script>

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

And mydiv.html did not have any <html> tags:

<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>

Solution

  • 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>