开发者

Adding alert() make "not working script" work properly

I have a to rewrite code written couple of years ago to work with modern browsers. That site includes couple of Javascript files.

In on of them there is a code something like this - it's generating DOM elements dynamically:

createTabs();
createTabsContent();

Now, I'm opening site in Chrome and after page is loaded I try to change some fresh generated element style by

document.getElementById('element').style.display = 'none';

and it's not working - either form script or Chrome console. Yes, element with id #element exists in DOM). What is wierd - Chrome doesn't reporting any errors.

But, when I modify code and do something like that:

alert('test'); //i put alert here 
createTabs();
createTabsContent();
//alert('test'); // or put it here

everything working properly.

In other browser开发者_开发知识库s: IE8, FF, Opera everything works, also no errors. I used jQuery document.ready, then tried with window.onload events - and they failed - nothing changed.

What may cause this behaviour?


This symptom of something DOM-related not working, but starting to work when an alert is added is usually solvable by deferring the second step:

this.foo();
var me = this;
setTimeout(function() { me.bar(); }, 0); // Whatever library you're using may provide a cleaner way of deferring execution.

IE is especially prone to things not instantly being ready to be interacted with. I haven't really encountered it much with Chrome.


When code "works" after you insert an alert, it usually means that there is some sort of race condition that you are bypassing by having the alert pause execution. For instance, you might have an AJAX request followed by a function call which is supposed to work on the AJAX result (however is called improperly after the AJAX request instead of being passed in to be called by the AJAX handler on completion). Without an alert, the function doesn't have the data yet, so it fails, but when you put an alert in, the request has the time needed to complete and the function succeeds.

It is hard to say for sure what the problem you are experiencing is due to without having more context about your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜