scriptタグをdocument.writeで出力する場合の動作
jsファイルの動的ロードはポピュラーな話題です。私も自分でdocument.writeで書き出したscriptタグが有効なのを見つけたときは驚きました。
これを利用してASPのincludeみたいなことができないかなと試行錯誤中ですが、どうも無理がある感じです。。。*1
原因の一つに、document.writeされたscriptタグの実行順序の問題があります。これはつまり、ページに書き込まれたタグの順番なわけですが、これがブラウザによって違う場合があるのです。
以下、サンプル。
[test.htm] <html> <head> <title></title> <script src="test1.js"></script> <script src="test2.js"></script> </head> <body onload="document.getElementById('test').value = document.body.parentNode.innerHTML;"> <textarea rows="20" cols="100" id="test"></textarea> </body> </html>
[test1.js] document.write("<script src='test11.js'></script>"); document.write("<script src='test12.js'></script>");
[test2.js] document.write("<script src='test21.js'></script>");
[test11.js] document.write("<script src='test111.js'></script>");
[test12.js](空ファイル)
[test111.js](空ファイル)
[test21.js](空ファイル)
document.body.parentNode.innerHTMLで、ページのソース(動的に書き込まれた部分も含む)を取得できます(onload後でないと使用できませんが)。これで出力されたscriptタグの順番を見てみます。
以下、scriptタグの順番です。
test1.js test11.js test12.js test111.js test2.js test21.js
test1.js test11.js test111.js test12.js test2.js test21.js
test111.jsファイルの位置に注目してください。
ポイントはjsファイル内で、document.writeにより複数のscriptタグが出力され、その最後以外のjsファイルで、更にdocument.writeによりscriptタグが出力された場合の、そのタグの挿入位置がブラウザによって違うということだと思います。(ややこしくてすみません・・・)
この違いに気が付くまでにかなり苦労しました・・・。