Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True client-side HTML includes

Tags:

html

jquery

ajax

HTML doesn't support client-side inclusion of other HTML, such as one gets for C with the #include directive. Instead, the dominant tools for client-side HTML inclusion appear to be iframe, object, and especially jQuery's .load. See this thread for examples.

Unfortunately, none of these methods seem to produce exactly the same DOM one would get from a #include. In particular, iframe and object wrap the included content in their respective tags. Also, the jQuery solution proposed in the example thread still results in a DOM with an extra div.

For example, consider the thread's jQuery solution:

a.html:

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#includedContent").load("b.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="includedContent"></div>
  </body> 
</html>

b.html:

<p> This is my include file </p>

This will create a DOM where the body part looks like:

<body> 
  <div id="includedContent">
    <p> This is my include file </p>
  </div>
</body>

but a true #include would not include the wrapping div, so the DOM would look like:

<body> 
  <p> This is my include file </p>
</body>

Any idea how to do a client-side include without the wrapper tags?

EDIT: I don't want to assume knowledge of the surrounding tags. For example, in this case the surrounding tag is body, but it won't be in all cases.

like image 465
emchristiansen Avatar asked Dec 03 '22 21:12

emchristiansen


2 Answers

Shameless plug of a library that I wrote the solve similar problem.

https://github.com/LexmarkWeb/csi.js

<div data-include="/path/to/include.html"></div>

The above will take the contents of /path/to/include.html and replace the div with it.

like image 81
Michael Marr Avatar answered Dec 07 '22 23:12

Michael Marr


I assume that your body has other elements or other inclusion tags like these, in which case you can use the callback of load to unwrap itself once the load is completed.

 $(function(){
   $("#includedContent").load("b.html", function(){
        $(this).contents().unwrap();
   }); 
});

You can isolate this callback function and use it for any other load that you'd be performing across.

   function unWrapPlaceholder(){
     $(this).contents().unwrap();
   }


    $(function(){
       $("#includedContent").load("b.html", unWrapPlaceholder); 
       $("#headerContent").load("h.html", unWrapPlaceholder); 
       $("#footerContent").load("f.html", unWrapPlaceholder); 
    });
like image 32
PSL Avatar answered Dec 08 '22 00:12

PSL