4 Methods of JS dynamic loading script _javascript skill

Source: Internet
Author: User
If the JS file is relatively small, or a JS good, so you can reduce the number of connections. Here are 4 more commonly used methods, you can choose according to the situation, the last cloud Habitat community will recommend one.
1, Direct document.write
Copy Code code as follows:

<script language= "JavaScript" >
document.write ("<script src= ' test.js ' ><\/script>");
</script>

2, dynamically changing the SRC attribute of the existing script
Copy Code code as follows:

<script src= ' id= "S1" ></script>
<script language= "JavaScript" >
S1.src= "Test.js"
</script>

3. Dynamically creating script elements
Copy Code code as follows:

<script>
var ohead = document.getElementsByTagName (' head '). Item (0);
var oscript= document.createelement ("script");
Oscript.type = "Text/javascript";
Oscript.src= "Test.js";
Ohead.appendchild (Oscript);
</script>

all three of these methods are executed asynchronously, that is, the script on the main page continues to run while the scripts are loaded, and if you use the above method, the following code will not get the desired result.
To dynamically load the JS script: A.js, the following is the contents of the file
Copy Code code as follows:

var str = "China";
Alert ("This is the variable in a.js:" + str);

Main Page code:
Copy Code code as follows:

<script language= "JavaScript" >
function Loadjs (ID, FILEURL)
{
var Scripttag = document.getElementById (ID);
var ohead = document.getElementsByTagName (' head '). Item (0);
var oscript= document.createelement ("script");
if (Scripttag) ohead.removechild (Scripttag);
Oscript.id = ID;
Oscript.type = "Text/javascript";
Oscript.src=fileurl;
Ohead.appendchild (Oscript);
}
Loadjs ("A.js");
Alert ("Main page dynamically loads A.js and takes the variables:" + str);
</script>

After the above code executes A.js's alert executes and pops up the message,
However, the main page generated an error, no pop-up dialog box. The reason is that ' str ' is undefined, why? Because the main page was a.js with STR, it was not fully loaded successfully. When you encounter a need to synchronize the execution of scripts, you can use the fourth method below.
4, principle: To use XMLHTTP to get the content of the script, and then create script object.
Note: A.js must be saved with UTF8 encoding, without error. Because the server and XML use UTF8 encoding to transmit data.
Main Page code:
Copy Code code as follows:

<script language= "JavaScript" >
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)
{
if (oxmlhttp.status = = | | oxmlhttp.status = 304)
{
Includejs (sId, URL, oxmlhttp.responsetext);
}
Else
{
Alert (' XML request error: ' + oxmlhttp.statustext + ' (' + oxmlhttp.status + ') ');
}
}
}
Oxmlhttp.open (' Get ', url, true);
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.language = "JavaScript";
Oscript.type = "Text/javascript";
Oscript.id = sId;
Oscript.defer = true;
Oscript.text = source;
Ohead.appendchild (Oscript);
}
}
Ajaxpage ("SCRA", "b.js");
Alert ("Home page dynamically loads the JS script.") ");
Alert ("Main page dynamically loads A.js and takes the variables:" + str);
</script>

Now completes the dynamic loading of a JS script.
Copy Code code as follows:

var rash=true;
var msg= "";
function Norash ()
{
if (Confirm (ok to cancel))
Rash=false;
}
function Rashit ()
{
SetInterval (' Getrss () ', inttime);
}
function Getrss ()
{
if (rash==true)
{
Head=document.getelementsbytagname (' head '). Item (0);
Script=document.createelement (' script ');
script.src= ' include/autoupdate.asp ';
Script.type= ' Text/javascript ';
Script.defer=true;
void (head.appendchild (script));
window.status=msg;
}
}
Rashit ();

Note that the text bold place, you can choose the situation.

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.