Include another HTML file in a HTML file

I have 2 HTML files, suppose a.html and b.html . In a.html I want to include b.html .

In JSF I can do it like that:

<ui:include src="b.xhtml" />

It means that inside a.xhtml file, I can include b.xhtml .

How can we do it in *.html file?


In my opinion the best solution uses jQuery:

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 method is a simple and clean solution to my problem.

The jQuery .load() documentation is here.


My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:

a.html:

<html> 
  <body>
  <h1>Put your HTML content before insertion of b.js.</h1>
      ...

  <script src="b.js"></script>

      ...

  <p>And whatever content you want afterwards.</p>
  </body>
</html>

b.js:

document.write('

    <h1>Add your HTML code here</h1>

     <p>Notice however, that you have to escape LF's with a '', just like
        demonstrated in this code listing.
    </p>

');

The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.

In order to get the properly escaped JavaScript file without much work, you can use the following sed command:

sed 's//\/g;s/^.*$/&/g;s/'''/'''/g' b.html > escapedB.html

Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js : https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.


Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files:

<script>
  $(function(){
    var includes = $('[data-include]');
    jQuery.each(includes, function(){
      var file = 'views/' + $(this).data('include') + '.html';
      $(this).load(file);
    });
  });
</script>

And then to include something in the html:

<div data-include="header"></div>
<div data-include="footer"></div>

Which would include the file views/header.html and views/footer.html

链接地址: http://www.djcxy.com/p/39532.html

上一篇: 过滤父母的孩子属性,但渴望

下一篇: 在HTML文件中包含另一个HTML文件