The behavior is not consistent across all browsers. Remember, on jsfiddle this code is already wrapped inside the window load callback since you chose the onLoad
setting on the left. Once the DOM is loaded, any subsequent changes using document.write
will replace the entire document.
Here's the relevant text from the HTML5 specs on document.write:
Unless called from the body of a script element while the document is being parsed, or called on a script-created document, calling this method will clear the current page first, as if document.open() had been called.
Here's how the browsers are behaving on my Mac given this code:
Chrome and Safari
Wipes out the document altogether. Even 100 isn't printed. Text nodes by themselves are being ignored here, but when wrapped inside some html tag - they show up. This code is the same as above with the values wrapped inside <b>
and <i>
tags respectively.
Opera and Firefox
Wipes out the document, then appends the text node "100undefined". It prints "undefined" because the node <div id="timers></div>
does not exist anymore in the new document.
However, it does print "100" the first time you call document.write
on Opera and Firefox
document.write($('#timers').data('firsttimer'));
because the function argument $('#timers').data('firsttimer')
is evaluated first and since the original document is intact at this point, we get the value 100, which is then passed to document.write
, that then recreates the entire document. Therefore, all subsequent calls to fetch the data associated with #timers
returns undefined.