Why javascript is not loading for document.readyState === "complete"

I just started learning javascript from w3school , and I found that "you can use document.write only for HTML output. If you use it after loading the document, the whole document will be overwritten." so I tried to write the following code to validate:

<html> <head> <title>ashish javascript learning</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <p> sample html with javascript </p> <script> document.write("<h1>this is heading</h1>"); document.write("<p>this is sample para</p>"); </script> <script> if(document.readyState === "complete"){ loaded(); } function loaded(){ document.write("<p>loading content after the document has been loaded"); } </script> </body> </html> 

The code still shows the old value and does not overwrite the contents of the web page. Could you suggest me what I am doing wrong.

+6
source share
6 answers

While you are testing document.readyState === "complete" , the readyState document is not "completed", it is "loaded", so nothing happens and loaded never called.

You can listen when the ReadyState changes, and then check if it is "full" (or simpler window.onload ):

 document.onreadystatechange = function () { if(document.readyState === "complete"){ loaded(); } } 
+12
source

Because the mechanism is event based. You should only use it after the DOM boots, so this is pointless.

The evaluation is done on site, but during the evaluation document.readyState == "complete" is false , so nothing happens.

A simple way to do something:

 window.onload = function() { loaded(); }; 
+4
source

What you need to do is connect the function to readystatechange , and then check the readystate value.

 document.onreadystatechange = function () { if (document.readyState === 'complete') { initApplication(); } } 
+3
source

write like this: you get the desired result

 document.onreadystatechange = function(){ if(document.readyState == 'complete'){ document.write('document is overwrite') } } 
0
source

sorry for the lack of explanation; when the code is executed in javascript, dom is not completed, so the readyState document is not "complete", then the initApplication funtion function will not be called; If you want to call the initApplication function, you need to add a trigger for the document. I am adding a trigger, e.g. document.onreadystatechange. "Document.onreadystatechange" will be called when the state of the document changes; therefore, when a document is loaded, "document.onreadystatechange" will be called

0
source

Great resource with a few examples and explanations: https://developer.mozilla.org/en/docs/Web/API/Document/readyState

So in your case this applies:

 document.onreadystatechange = function () { if (document.readyState === "complete") { initApplication(); } } 
0
source

Source: https://habr.com/ru/post/944579/


All Articles