続:JavaScriptを使ってHTMLのインクルードを実現しつつ、JSPでもインクルードできる方法

前のエントリで書いたHTMLのインクルードの改良版。だいぶすっきりできました。


●呼び出しイメージ
<script type="text/javascript" >//<%
document.include("a.txt",request,response); //%>
</script>


スクリプト本体
<script type="text/javascript" >

document.include = function(filename) {
this.include.seq = (this.include.seq)? this.include.seq + 1: 1;

var id = new Date().getTime() + "-" + this.include.seq;
var inc = document.createElement("iframe");

inc.id = "inc-" + id;
inc.src = filename;
inc.style.display = "none";
document.body.appendChild(inc);
document.write("<span id=\"" + id + "\"></span>");

var f = function() {
inc = document.getElementById("inc-" + id);
var s = inc.contentWindow.document.body.firstChild.innerHTML;
document.getElementById(id).innerHTML =
s.split("&gt;").join(">").split("&lt;").join("<");
document.body.removeChild(inc);
};
if (window.addEventListener) window.addEventListener('load', f, false);
if (window.attachEvent) window.attachEvent('onload', f);
};

/*<%!
interface Document {
void include(String filename);
}
%><%
Document document = new Document() {
void include(String filename) throws Exception {
out.print("</script>");
req.getRequestDispatcher(filename).include(request, response);
out.print("<script type='text/javascript'>");
}
};

/**///%>


JSPでも無名関数を使う事で、request, response を引数で渡さなくてもよくなります。これは便利な使い方だ。