In general, if the script is very long, we put them into a JS file, then generate a script element, add it to the DOM tree, and set SRC to the address of the JS file. But for very short scripts, what if we don't want to use new functions and eval? There is also a way to use the text and non-standard attributes of the script element, which are supported by all mainstream browsers. It is a bit like innerhtml, but innerhtml can only convert strings into various nodes, but cannot parse scripts. See the following example:
VaR script = Document. createelement ('script'); script. type = 'text/JavaScript '; script. Text = "alert (' This is dynamically added! ') "; Document. Body. appendchild (SCRIPT );
<Br/> <! Doctype HTML> <br/> <title> script. text by situ zhengmei </title> <br/> <meta charset = "UTF-8"/> <br/> <meta name = "keywords" content = "script. text by situ zhengmei "/> <br/> <meta name =" Description "content =" script. text by situ zhengmei "/> <br/> <SCRIPT type =" text/JavaScript "> <br/> window. onload = function () {<br/> var script = document. createelement ('script'); <br/> script. type = 'text/JavaScript '; <br/> script. TEXT = "alert ('This is dynamically added! ') "; <Br/> document. body. appendchild (SCRIPT); <br/>}< br/> </SCRIPT> <br/> <H2> script. text by situ zhengmei </H2> <br/>
Run code
|
Text |
Innerhtml |
Textcontent |
Cteatetextnode |
| IE6 |
● |
× |
× |
× |
| IE8 |
● |
× |
× |
× |
| Ff3.6 |
● |
● |
● |
● |
| Chrome5 |
● |
● |
● |
● |
| Safari4 |
● |
● |
● |
● |
| Opera10.10 |
● |
× |
● |
● |