Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have just started learning javascript from w3school and I have found out that "You can only use document.write in the HTML output. If you use it after the document has loaded, the whole document will be overwritten." so I have tried to write following code to check the validity:

<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>

Code is still showing the old value and is not overwriting the content of the web page. Could you suggest me what am I doing wrongly.

like image 942
Ashish Avatar asked May 08 '13 22:05

Ashish


1 Answers

At the time you're testing document.readyState === "complete", the document's readyState isn't "complete", it "loading", so nothing happens, and loaded is never called.

You can listen for the readyState to change, and then check to see if it is "complete" (or listen to window.onload which is easier):

document.addEventListener('readystatechange', e => {
  if(document.readyState === "complete"){
    loaded();
  }
});
like image 83
meagar Avatar answered Sep 29 '22 13:09

meagar