How exactly does document.write function in JavaScript?

Currently, I am delving into JavaScript through W3Schools and have encountered a statement that says "If you execute document.write after the document has finished loading, the entire HTML page will be overwritten." From the examples provided, I have noticed this phenomenon occurring, but the explanation seems to be a bit unclear on what exactly is happening. I decided to experiment by rearranging parts of the script to see if it would alter the outcome, but to no avail.

<h1>My First Web Page</h1>

<p>My First Paragraph</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>

</body>
</html>

As I strive to grasp the concept better, I would appreciate any insights or brief summaries on how this process actually functions. Understanding this will enable me to proceed with my learning journey seamlessly.

Answer №1

If you have a background in programming, you likely understand the concept of streams. Streams are used to represent a continuous flow of data that can be read from or written to, typically without the ability for random access.

Just think of the document object as containing a hidden stream within it that holds the raw text response from a web server, such as HTML content. By using the document.open() method, you can access this stream.

During the loading process of a webpage, the document stream is already open and actively being read from or written to as the bytes arrive from the server to your browser. Once the document finishes loading (the HTML content specifically, not external resources like <img />), the stream is closed.

This is why using document.write while a page is loading, like

<script>document.write("foo");</script>
, directly inserts "foo" into the document stream. However, if you use document.write after the document has finished loading, it essentially reopens the stream from the beginning, overwriting anything previously written.

Answer №2

The outcome varies depending on the browser you're using. In the past, your code would have replaced the entire page with text in all browsers. However, recent changes in some browsers mean that the document.write call may now be ignored instead of automatically calling document.open if it hasn't been called already.

It is still possible to use document.write after the page has loaded to replace the content in all browsers. But, this must be done correctly by first calling document.open.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

Difficulty encountered in altering button color when the password and confirm password fields are the same in a Vue.js project?

password: '', confirmPassword: '', computed: { empty() { return this.user.password === '' || this.user.confirmPassword === ''; }, equal() { return this.user.password === this.user.confirmPass ...

Sharing a boolean state between two pages using Material UI components

One challenge I've been facing is passing a boolean useState value between two pages. I found a helpful solution on this Stack Overflow thread: How to call useState from another Page? The main goal here is to display a success alert on a separate pag ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

Ways to verify if all files have been loaded using Firebase.util pagination

Is there a way to confirm if it is necessary to stop invoking the loadMore() function, since all documents have been retrieved from the database? In the code snippet provided, Ionic framework is used as an example, but the same concept applies to ng-infin ...

Retrieve information from ngResource (angularjs) based on the chosen item

I am currently developing a small application that needs to display a list of cities only when a country is selected using ngResource in angularjs. The problem I am facing is that the entire list of countries and cities is being rendered initially, causing ...

A compilation of web browsers and their compatible versions for the SVG engine

I recently encountered an issue with the org chart I created using getorgchart. Everything was running smoothly until I tested it on IE8. It turns out that getorgchart relies on the SVG engine for rendering, which is not supported by IE8. I attempted to ...

Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method. For instance, let's say I have four options: A B C D In my method (let's use "x" as an example): if(name == A) { disable the selection for option A. ...

Transitioning from Three.js's CanvasRenderer to WebGLRenderer is a significant upgrade

Can a Three.js script created with CanvasRenderer be easily converted to use WebGLRenderer instead, and if yes, what is the process for doing so? ...

Utilize the outcome of one variable to label another variable

I am attempting to generate a variable name by using the id value of another variable. Here is my approach: Upon clicking one of the 4 tables, I get the id of the table. For instance, let's say it's 676. Next, I want to create a variable using ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

Using Moment JS to Retrieve Month Names from the Current Year Starting from the Current Month and Beyond

In my quest for knowledge, I desire to ascertain the name of the current month and also list out the remaining months in the current year that have yet to pass. As an illustration, if the current month is July and we are in the year 2021, the months of Aug ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Expand and collapse divs using jQuery when a JavaScript do_PostBack link is clicked

Currently, I am in the process of developing a website called TheDigitalScale. One particular feature on the site involves using jQuery to create an expanding div that opens when clicked and closes with another click. <script type="text/javascript"> ...

Tips for Drawing Lines and Preserving Them When a Condition is Met

I am currently utilizing Node.Js in an attempt to outline objects within an image based on certain conditions being met. My goal is to draw lines around specific portions of the image received from an API response. Whenever the response includes the keywor ...

Setting the rotation position in JQuery prior to initiating the animation

Perhaps I could phrase my query differently as How can I rotate an image in JQuery from a starting position other than 0 degrees. I am attempting to animate the rotation of an image from -50deg to 0deg. However, regardless of what I do, JQuery seems to al ...

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE". Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imp ...