1

Does anybody have any idea why the following code will be executed in different order in different browsers? Code is in an external file embedded in a plain HTML page between <body></body> using <script src="js/filename.js"></script>.

document.write("This is the first document.write()");

document.write("<br />followed by a second doc.write with br-element before");

document.write("<br /> and a third one doc.write with br before");

alert("now comes an alert() as fourth (will be expected)");

document.write("<br /> then there will be a fifth doc.write after the first alert");

document.write("<br />and a one more (sixth) doc.write after which an alert will be expected");

alert("the second alert at seventh position");

document.write("<br />and now the eight doc.write after the seventh alert");

Chrome executes the alerts at first followed by the docWrites, Edge execute the first 3 docWrite's, then both alerts and then the other docWrite's (also wrong order). Only Firefox execute this code in the right order.

Same behavior is when I execute similar code in developer tool of the browser(s) for example: write in one line an document.write(); followed by an alert(). Chrome will execute the alert() as first...

Does anyone have any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dusko
  • 11
  • 1
  • 2
    Writing to the document is an internal process--it may be buffering, for example. Threads like https://forums.asp.net/t/955514.aspx?document+write+doesn+t+write+until+javascript+function+terminates+ may help, but please take note of what's discussed in the whatwg living spec: https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write – Dave Newton Jul 24 '19 at 17:11
  • 2
    I'm pretty certain the statements are executed in order, but the document might not yet be re-rendered when the `alert()` box appears. Notice that both `document.write` and `alert` are outdated and bad practices, don't use them. – Bergi Jul 24 '19 at 17:15
  • Tnx both of you. @Bergi, yes I know it is bad practice to use both. I just tried some fundamentals and thorough this testings I figgured out this behavior and I did not understand WHY this happens. But you gived to me a good idea with loading of the document and also Dave's links was helpfull. Now I can "imagine" why browser makes so stupind things. This is why I love JS so much. The results sometimes have so suprising effects :-))) – Dusko Jul 24 '19 at 19:15
  • @AJS I'm not so sure about that. I think this is purely an odd buffering effect. None of the code written here should be performed asynchronously. – StardustGogeta Jul 26 '19 at 12:57

0 Answers0