Is it safe to call document.write () inside the <script> tag?

If I call document.write () inside the script tag, can I trust that it will execute simultaneously in the main browsers (i.e. during page load and before the onload event)?

Also, will this work with major browsers:

  <script ...>
     if (condition)
        document.write('<div ...>');
     else
        document.write('<span ...>');
  </script>
      ... // some content.

  <script ...>
     if (condition)
        document.write('</div>');
     else
        document.write('</span>');
  </script>

?

+3
source share
3 answers

If script tags are not deferred ( <script defer>), they are run in the order in which they are displayed, and if they are inside <head>or <body>, then they will be executed before onload.

Use document.writeafter loading the body (after the document is actually closed) is dangerous because it will blow away the document. So

setTimeout(function () { document.write('O Hai'); }, 1000)

A good way to deflate your document.

, , , , , script script , script . , ,

<script>
if (Math.random() < 0.5) {
  document.write("<script>");
}
</script>
alert('One'); /*
<script>
alert('Two');
//*/</script>
+4

onload. , jquery, $(document).ready()

+1

The definition of document.write is that it will write content in the exact location of document.write. This behavior is consistent across browsers.

0
source

All Articles