Index.html
[HTML]View Plaincopy
- <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta content= "text/html;charset=utf-8" http-equiv="Content-type">
- <title> </title>
- <script src=' id="S1"></script>
- <script src="Dynamic.js"></script>
- </head>
- <body>
- </Body>
- </html>
Test.js
[HTML]View Plaincopy
- Alert ("Hello! I am Test.js ");
- var str="1";
Dynamic.js
[JavaScript]View Plaincopy
- The first way: direct document.write But this will put the current page full overwrite
- document.write ("<script src= ' test.js ' ><\/script>");
- Second way: Dynamically changing the SRC attribute of an existing script
- S1.src= "Test.js"
- Third Way: Dynamic creation of script elements
- /* var ohead = document.getelementsbytagname (' HEAD '). Item (0);
- var oscript= document.createelement ("script");
- Oscript.type = "Text/javascript";
- Oscript.src= "Test.js";
- Ohead.appendchild (Oscript);
- */
- In fact, the principle is to use the DOM dynamic introduction of a JS to the file to ~ can and the original JS communication ~
- alert (str);
- /* More than three ways to use the asynchronous loading mechanism, which is the loading process, the page will go down,
- If this is problematic, such as the above STR is inaccessible, because when the program executes alert (STR), test.js is still loading ing ....
- <strong><span style= "color: #ff0000;" > So the fourth is based on Ajax requests, and is recommended </span></strong>
- */
- function Gethttprequest ()
- {
- if (window. XMLHttpRequest) //Gecko
- return new XMLHttpRequest ();
- Else if (window. ActiveXObject) //IE
- return new ActiveXObject ("msxml2.xmlhttp");
- }
- function ajaxpage (sId, url) {
- var oxmlhttp = Gethttprequest ();
- Oxmlhttp.onreadystatechange = function ()
- {
- if (oxmlhttp.readystate = = 4)
- {
- Includejs (sId, URL, oxmlhttp.responsetext);
- }
- }
- Oxmlhttp.open (' GET ', URL, false); Synchronous Operation
- Oxmlhttp.send (null);
- }
- function Includejs (sId, FILEURL, source)
- {
- if (source = null) && (!document.getelementbyid (sId))) {
- var ohead = document.getelementsbytagname (' HEAD '). Item (0);
- var oscript = document.createelement ( "script");
- Oscript.type = "Text/javascript";
- Oscript.id = sId;
- Oscript.text = source;
- Ohead.appendchild (Oscript);
- }
- }
- Ajaxpage ( "SCRA", "test.js");
- Alert ( The main page dynamically loads the JS script. ");
- Alert ( "The main page dynamically loads the A.js and takes the variables:" + str);
Four ways to introduce JS dynamically