Javascript dynamic parsing script

Source: Internet
Author: User

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 ×

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.