サブカラムやフッターなど他のページで使いまわすような要素はincludeやrequire、SSIなどで外部ファイルを読み込んで対応している人は多いかと思われます。実際そっちの方が更新も楽ですし、ケアレスミスも少ないです。(あったとしても外部ファイル1つ直せば済みます。)
それをJavascriptで実現できる方法を見つけたので紹介いたします。
javascript
function include(filename, afterfunc) { include.seq = (include.seq)? include.seq + 1: 1; var id = new Date().getTime() + "-" + include.seq; var inc = document.createElement("iframe"); inc.id = "inc-" + id; inc.src = filename; inc.style.display = "none"; document.write("<span id=\"" + id + "\"></span>"); var incfunc = function() { var s = (function() { var suffix = (n = filename.lastIndexOf(".")) >= 0 ? filename.substring(n): "default"; if (suffix == ".html") return inc.contentWindow.document.body.innerHTML; if (suffix == ".txt") return inc.contentWindow.document.body.firstChild.innerHTML; if (suffix == "default") return inc.contentWindow.document.body.innerHTML; })(); var span = document.getElementById(id); var insertBeforeHTML = function(htmlStr, refNode) { if (document.createRange) { var range = document.createRange(); range.setStartBefore(refNode); refNode.parentNode.insertBefore(range.createContextualFragment(htmlStr), refNode); } else { refNode.insertAdjacentHTML('BeforeBegin', htmlStr); } }; insertBeforeHTML(s.split(">").join(">").split("<").join("<"), span); document.body.removeChild(inc); span.parentNode.removeChild(span); if (afterfunc) afterfunc(); }; if (window.attachEvent) { window.attachEvent('onload', function() { document.body.appendChild(inc); inc.onreadystatechange = function() { if (this.readyState == "complete") incfunc(); }; }); } else { document.body.appendChild(inc); inc.onload = incfunc; } }
インクルード部分
<div> <script type="text/javascript" > include("a.html"); ←HTML内のインクルードしたいところに記入 </script> </div>
インクルードされるファイル(a.html)
<div style="border: solid 1px #000000;">hello;</div>
■参考サイト:
静的HTMLで、インクルードを実現するためのJavaScript
http://d.hatena.ne.jp/kenpoco/20080501/1209636103
ホームページビルダー・G初心者講座 – [jQuery][Ajax]別のhtmlファイルやテキストファイルを読み込む
http://www.aimix.jp/jquery_ajax.html
特にcgi周りですと、phpが使用できないので重宝します。
うまく説明ができませんが、php includeではセッション切れをおこして動作しなかったものをこちらのJavascriptにするとうまく動作してくれました。
ただ動作しないブラウザなどもあるらしいので、導入する時は入念なチェックが必要ですね。