0

JavaScript Testing query

If I write the following code for testing JavaScript : document.write("Hello World!"); alert("Hello"); Why alert tag opens first?

4th Nov 2017, 6:21 AM
Nikhil Sharma
Nikhil Sharma - avatar
2 Answers
+ 4
JS in web pages is single threaded, meaning only one script can run at a time... Alert(), prompt() and confirm() execute modal pop-ups, meaning, while there are unclosed, everything on page is stopped, waiting for user interaction: everything mean also the display refresh, so even if your document.write occurs before your alert() (and DOM is already updated according to that), the display engine don't still have updated the viewport, wich can only occurs when JS script end and release cpu... One way to "force" display to be refreshed as soon as possible is to delay your next code asynchrously (technically, your JS script end, and a process wait to run another part -- a function -- letting the page content refresh be displayed: it could be useful in long loop, when you want to show progress of a computation for example) using setTimeout() or even setInterval()... function main() { document.write("Hello World!"); setTimeout(next,150); } function next() { alert("Hello"); } Calling main() will execute it, and then execute next(), waiting for 150ms seconds between, to let time to display engine to refresh and reflect the change before executing the alert (in this -- very -- simple case, we could directly wrote: setTimeout(alert,150,"Hello"); ^^)
4th Nov 2017, 9:05 AM
visph
visph - avatar
0
Browsers vary in how they handle document writes during initial page load. Previously, it was common for browsers to display the page while it was being constructed. But most modern browsers do not display the page until all loading (including the running of any JavaScript) is completed. So now, in most browsers, you will see any alert or prompt statements as they execute, but you will only see the results of document.write after the entire script is finished.
4th Nov 2017, 6:25 AM
Cool Codin
Cool Codin - avatar