Monday, 21 September 2015

document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page depending on where it is being called.

For e.g.,

<html>
<head></head>
<body>
<p>The current date and time is,
<script type="text/javascript">
document.write((new Date()).toString());
</script>
</p>
</body>
</html>

Output: The current date and time is, Sun Sep 20 2015 01:23:01 GMT+0530 (India Standard Time)

In the above example, document.write() has been used to output content directly into the page as it’s being rendered.

If document.write() is called after the page has been completely loaded, the content
overwrites the entire page (existing DOM), as shown in the following example:

<html>
<head></head>
<body>
<p>The current date and time is,
<script type="text/javascript">

window.onload = function(){
    document.write((new Date()).toString());
}
</script>
</p>
</body>
</html>

In the above example, document.write() is called after the page has been completely loaded by using the window.onload event handler.
So, the text:

"Sun Sep 20 2015 01:23:01 GMT+0530 (India Standard Time)"

is only rendered, overwriting the text:

"The current date and time is,"

Similar incident occurs with jQuery $(document).ready()

It's better to avoid document.write. You may use document.createElement instead.

No comments:

Post a Comment

document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page d...