Ahu Lee Ahu Lee - 2 months ago 7
Javascript Question

Firefox + some javascript = tab with an endless spinning wheel that never finish loading (Chrome is okay!). Why?



function clickMe() {
document.write("You clicked on the Button!");
}

<html>
<body>
<script src="script.js"></script>
<input type="button" value="Button" onclick="clickMe()" />
</body>
</html>





Pressing the button here causes the Firefox tab loading wheel to spin forever. Why is that?

Are there any errors in the code or maybe this is some Firefox issue?

Thank you so much!

Answer

From the documentation

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call.

Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page.

So whenever you call document.write on a document that has already finished loading, like you're doing with an event handler, the entire document is overwritten, and document.open is called automatically, but as the document never finishes loading and calls document.close, the loading wheel keep spinning.

Apparently different browsers do different things, and it's not specifically specified wether or not they should just "hang" forever or not.

As document.write should generally never be used anyway, this is really not an issue, just replace it with a proper method that modifies the DOM instead of overwriting the entire document.