bodyができるのを待ち合わせる
・・・・・ <script type="text/javascript"> ・・・・・ var test = function(){ alert($i('test')); } test(); ・・・・・ </script> </head> <body> <div id="test"></div> </body> ・・・・・
みたいな事をよくやってしまうので待ち合わせてしまえと。
document.bodyより先に書いたscript内でよくdocument.body内の要素をいじろうとしてエラーになっちゃう人って多そうなのでこんなの作ってみた。
kumu.js
init : function(){ /* ... */ /* onloadでフラグを立てちゃえ><*/ var loaded = function(){ Kumu._contentLoaded = true; } var unloaded = function(){ if (window.removeEventListener) { window.removeEventListener('load', loaded, false); } else if (node.detachEvent) { window.detachEvent('onload', loaded); } } var windowEvent = function(name, func){ if (window.addEventListener) { window.addEventListener('load', loaded, false); } else if (node.attachEvent) { window.attachEvent('onload', loaded); } } windowEvent('load', loaded); windowEvent('unload', unloaded); }, /* ... */ Kumu.init();
とまあ単純にフラグを立てておけばいいだけかなあと。
で待ち合わせ関数の作成はこんな感じ
Function.prototype.waitLoaded = function(){ var x = this; if(Kumu._contentLoaded){ return this; } var time = 500; var timeout; var args = []; var timerEvent = function() { if(Kumu._contentLoaded){ var o = x.apply(x, args); clearInterval(timeout); return o; } } var func = function(){ for(var i = 0; i < arguments.length;i++){ args.push(arguments[i]); } timeout = setInterval(timerEvent, time); } func.origin = x; func.clear = function(){ if(timeout){ clearInterval(timeout); } } return func; }
定期的に見に行くっていうめんどい方を書いてみた。
でも実はKumu.Eventに
Function.prototype.registEvent = function(scope){ if(!scope){ scope = {}; } var ret; if(this.__name){ ret = this.__name; }else{ ret = this.getName(); } var arr = Kumu.separate(ret); var callback = this.bindScopeAsEventListener(scope, arr[1]); Kumu.Event.addEvent(arr[1], arr[0], callback, false); } Function.prototype.registOnLoad = function(scope){ this.__name = 'window_load'; this.registEvent(scope); }
っていうステキな物を作っていた事を思い出したので全くもってクソエントリになってしまったなあと思いつつ今日はこの辺で。
※監視するobjを引き数で渡せるようにすればとある条件を満たすまで一定時間に実行するようなものもできたりするんだろうけどでもjsだとやっぱ意味なさげ。
うくく。