ページを表示した時点でJavaScriptを実行したい場合、
>
<
window.onload=function(){ alert('called when window is loaded.'); }
のようにwindowオブジェクトのonloadイベントに実行したいfunctionをセットしてやればいいのですが、これだと、オンロード時にひとつのfunctionしか実行できません。
そこで、オンロード時に複数のfunctionを実行できるようなスクリプトを書いてみました。今回のコードはnaoyaさんのprototype.js でデザインパターン - IteratorのエントリにあるIteratorパターンのコードをそのまま借りたリスペクト指向プログラミングになってますw
>
<
//multiple_onload.js
var OnloadFunction = Class.create();
OnloadFunction.prototype = {
initialize : function(func) {
this.func = func;
},
getFunc : function() {
return this.func;
}
};
var OnloadFunctions = Class.create();
OnloadFunctions.prototype = {
initialize : function() {
this.last = 0;
this.functions = new Array();
},
getFunctionAt : function(index) {
return this.functions[index];
},
appendFunction : function(func) {
this.functions[this.last] = func;
this.last++;
},
getLength : function() {
return this.last;
},
iterator : function() {
return new OnloadFunctionIterator(this);
}
}
var OnloadFunctionIterator = Class.create();
OnloadFunctionIterator.prototype = {
initialize : function(functions) {
this.functions = functions;
this.index = 0;
},
hasNext : function () {
return this.index < this.functions.getLength();
},
next : function() {
return this.functions.getFunctionAt(this.index++);
}
}
var onloadFunctions = new OnloadFunctions();
function multipleOnload () {
var it = onloadFunctions.iterator();
while (it.hasNext()){
var func = it.next();
func.func();
}
}
window.onload = multipleOnload;
使用方法はこんな感じです。
動作させるにはprototype.jsが必要なので最初にインクルードしています。
>
<
<html>
<head>
<script type="text/javascript" src="/js/prototype-1.3.1.js" ></script>
<script type="text/javascript" src="/js/multiple_onload.js" ></script>
<script type="text/javascript">
functon foo() {alert('foo');}
functon bar() {alert('bar');}
functon baz() {alert('baz');}
onloadFunctions.appendFunction(new OnloadFunction(foo) );
onloadFunctions.appendFunction(new OnloadFunction(bar) );
onloadFunctions.appendFunction(new OnloadFunction(baz) );
</script>
</head>
<body>
...
</body>
</html>
まず、multiple_onload.jsをインクルードしておきます。そして、定義したfunctionをappendFunctionメソッドを使ってセットしておきます。
これでfoo,bar,bazがオンロード時に順番に実行されます。


