Js document.write of

  • 2020-03-30 02:03:47
  • OfStack

Document. The write method

One of the most basic JavaScript commands is document.write. This command simply prints the specified text content to the page. To print text verbatim, put single quotes around the printed text string.


document.write('Hello World!');  

The above js code will display "Hello World!" on the page.
You can print variables using document.write. Input variable name without quotes, as follows:


var mytext = "Hello again";
document.write(mytext);

Note: if the variable name is quoted, the variable name is printed (the variable value is not printed). You can use the "+" symbol to connect variable values to text strings.


var colour1 = "purple";   
var colour2 = "pink";
document.write('<p>colour1: ' + colour1 + '<br>colour2: ' + colour2 + '</p>');  

The print result is as follows:

Colour1: purple
Colour2: pink

Document.write is also used to load js ads


document.write('<scri'+'pt src="//www.jb51.net/ad.js" type="text/javascript"></s'+'cript>');
document.write("<scri"+"pt src='//www.jb51.net/ad.js' type='text/javascript'></s"+"cript>");
document.write("<scri"+"pt src="//www.jb51.net/ad.js" type="text/javascript"></s"+"cript>");

Generally use single quotation marks (double quotation marks) to concatenate characters outside, and double signals (single quotation marks) inside, so that there is no mistake. Of course, escape characters can also be used, but this is more cumbersome to modify later.

Document.write loads js asynchronously


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="ru">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">    
    </head>    
    <script type="text/javascript">
    function load(js){
    var s = document.createElement('script');  
    s.setAttribute('type','text/javascript');  
    s.setAttribute('src',js);  
    var head = document.getElementsByTagName('head');  
    head[0].appendChild(s);  

    }
    function write(js){
    document.write('<script type="text/javascript" src="'+js+'" > </script>');
    }   

           load("//www.jb51.net/js/2011/jquery-1.5.1.min.js"); 
          // write("//www.jb51.net/js/2011/jquery-1.5.1.min.js");

   </script>
<script>
alert($);
</script>

Q: load with createElement("script"), and the function will report an error, document.write will not report an error?

The answer:

Different browsers have different reactions to dynamically created js references    
For FF Opera, the load method is blocked so alert($) outputs, while for IE, Chrome, Safria is non-blocked so it reports an error.
And the document.write way, which is blocked for all browsers is synchronized so alert($) will print the correct result


Related articles: