Four Methods for loading scripts dynamically in JS

Source: Internet
Author: User

If the js files are relatively small and a js file is better, this can reduce the number of connections. The following are four commonly used methods. You can select one method based on your needs.
1. Directly document. write
Copy codeThe Code is as follows:
<Script language = "javascript">
Document. write ("<script src = 'test. js'> <\/script> ");
</Script>

2. dynamically change the src attribute of an existing script
Copy codeThe Code is as follows:
<Script src = ''id =" s1 "> </script>
<Script language = "javascript">
S1.src = "test. js"
</Script>

3. dynamically create script elements
Copy codeThe Code is 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>

These three methods are executed asynchronously. That is to say, when these scripts are loaded, the scripts on the home page continue to run. If the above method is used, the following code will not achieve the expected results.
JS script to be dynamically loaded: a. js. The content of this file is as follows:
Copy codeThe Code is as follows:
Var str = "China ";
Alert ("this is the variable in a. js:" + str );

Homepage code:
Copy codeThe Code is 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 ("loading a. js dynamically on the homepage and taking the variable:" + str );
</Script>

After the above code is executed, alert of a. js is executed and a message is displayed,
However, an error occurs on the home page. No dialog box is displayed. The reason is that 'str' is not defined. Why? This is because when str is retrieved on the homepage, a. js is not fully loaded. When you need to execute the script synchronously, you can use the fourth method below.
4. Principle: Use XMLHTTP to get the content of the Script and create a Script object.
Note: a. js must be UTF-8 encoded and saved without errors. Because the server and XML use UTF8 encoding to transmit data.
Homepage code:
Copy codeThe Code is 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 = 200 | 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 compute dejs (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 ("the main page dynamically loads JS scripts. ");
Alert ("loading a. js dynamically on the homepage and taking the variable:" + str );
</Script>

Now a JS script is loaded dynamically.
Copy codeThe Code is as follows:
Var Rash = true;
Var msg = "";
Function norash ()
{
If (confirm ("are you sure you want 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 is bold and you can choose the appropriate one.

Related Article

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.