【HTML】共通ファイルを使用する

AjaxでHeader・Footerを共通化する方法

Ajaxを使用したheaderとfooterの共通化【JavaScript】

簡単に説明すると定義した関数内にAjaxで共通HTMLを読み込む処理を書き、表示用HTML内で関数を実行することで共通化します。

HTML

headerタグ・footerタグの中身を共通ファイルとして読み込む。

<header id="site-header" class="site-header">
  <script>include_header();</script>
</header>
.
<footer class="site-footer">
  <script>include_footer();</script>
</footer>

jQuery

function include_footer(){
  $.ajax({
    url: '/include/footer.html',
    async: false,
  }).done(function(footer_html){
    document.write(footer_html);
  });
}

function include_header(){
  $.ajax({
    url: '/include/header.html',
    async: false,
  }).done(function(header_html){
    document.write(header_html);
  });
}
  • X